Ejemplo n.º 1
0
        private void UpdateDependency(string nameDependency, string previous, string latest)
        {
            var path = AppodealDependencyUtils.Network_configs_path + nameDependency +
                       AppodealDependencyUtils.Dependencies + ".xml";

            if (!File.Exists(path))
            {
                AppodealDependencyUtils.ShowInternalErrorDialog(this,
                                                                "Can't find config with path " + path, $"path - {nameDependency}");
            }
            else
            {
                string contentString;
                using (var reader = new StreamReader(path))
                {
                    contentString = reader.ReadToEnd();
                    reader.Close();
                }

                contentString = Regex.Replace(contentString, previous, latest);

                using (var writer = new StreamWriter(path))
                {
                    writer.Write(contentString);
                    writer.Close();
                }
            }
        }
Ejemplo n.º 2
0
        private void ImportConfig(string nameDep, string content)
        {
            var path = AppodealDependencyUtils.Network_configs_path + nameDep + AppodealDependencyUtils.Dependencies +
                       AppodealDependencyUtils.XmlFileExtension;

            if (File.Exists(path))
            {
                UpdateDependency(nameDep, AppodealDependencyUtils.SpecCloseDependencies,
                                 content + "\n" + AppodealDependencyUtils.SpecCloseDependencies);
                AppodealDependencyUtils.FormatXml(System.IO.File.ReadAllText(path));
            }
            else
            {
                using (TextWriter writer = new StreamWriter(path, false))
                {
                    writer.WriteLine(AppodealDependencyUtils.SpecOpenDependencies
                                     + content + "\n" + AppodealDependencyUtils.SpecCloseDependencies);
                    writer.Close();
                }

                AppodealDependencyUtils.FormatXml(System.IO.File.ReadAllText(path));
            }

            UpdateWindow();
        }
Ejemplo n.º 3
0
        public static string GetCachedPath(CardData data)
        {
            var url = data.Image;

            if (string.IsNullOrEmpty(data.Title))
            {
                data.Title = "default";
            }

            string imageName = string.Format(cachedImageNameFormat, data.Title, data.Id);
            string fileName  = Application.persistentDataPath + "/" + Path.GetFileName(imageName);

#if !UNITY_WINRT
            if (File.Exists(fileName))
            {
                url = "file://" + fileName;
            }
            else
#endif
            {
                url = AzureMuseumImageFormatter.GetImageUri(url, 277, 274).ToString();
            }

            return(url);
        }
Ejemplo n.º 4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="fileName"></param>
 public static void Delete(string fileName)
 {
     if (Exists(fileName))
     {
         File.Delete(fileName);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Deletes the specified file.
        /// </summary>
        /// <param name="_filePath">The name of the file to be deleted.</param>
        public static void Delete(string _filePath)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported.");
#else
            File.Delete(_filePath);
#endif
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
        /// </summary>
        /// <param name="_filePath">The file to write to.</param>
        /// <param name="_bytes">The bytes to write to the file.</param>
        public static void WriteAllBytes(string _filePath, byte[] _bytes)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported");
#else
            File.WriteAllBytes(_filePath, _bytes);
#endif
        }
Ejemplo n.º 7
0
 public void LoadSave()
 {
     if (File.Exists(_saveFilePath))
     {
         var saveToLoad = JsonConvert.DeserializeObject <Save>(File.ReadAllText(_saveFilePath));
         LoadSaveGameObject(saveToLoad);
     }
 }
Ejemplo n.º 8
0
        private void LoadFileChangeLog()
        {
            var filePath = Path.Combine(Application.dataPath, fileName);

            if (File.Exists(filePath))
            {
                _changeLoggerStr = JsonFile.LoadJsonFile <string>(filePath);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Write contents to a file
        /// </summary>
        /// <param name="path">Path of the file</param>
        /// <param name="contents">Contents of the file</param>
        public static void Write(string path, string contents)
        {
#if UNITY_WINRT && !UNITY_EDITOR
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(contents);
            File.WriteAllBytes(path, bytes);
#else
            File.WriteAllText(path, contents);
#endif
        }
 private void EnsurePluginSelected()
 {
     if (!File.Exists(_config.IlWeaverPluginExecutablePath))
     {
         EditorUtility.DisplayDialog("Error",
                                     $"Unable to find plugin, please make sure that '{PluginExecutablePathLabel}' is correct.", "Pick file");
         SelectPluginViaPicker();
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Determines whether the specified file exists.
        /// </summary>
        /// <returns><c>true</c>, if file exists at given path, <c>false</c> otherwise.</returns>
        /// <param name="_filePath">The file to check.</param>
        public static bool Exists(string _filePath)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported.");
            return(false);
#else
            return(File.Exists(_filePath));
#endif
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
        /// </summary>
        /// <returns>The file contents as byte array.</returns>
        /// <param name="_filePath">The file to open for reading.</param>
        public static byte[] ReadAllBytes(string _filePath)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported");
            return(null);
#else
            return(File.ReadAllBytes(_filePath));
#endif
        }
Ejemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="password">Can be null or empty</param>
        public PDFDocument(string filePath, string password)
        {
            PDFLibrary.AddRef("PDFDocument");

#if !UNITY_WEBPLAYER
            CommonInit(File.ReadAllBytes(filePath), password);
#else
            m_ValidDocument = false;
#endif
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Moves the specified file to destination path.
        /// </summary>
        /// <param name="_sourcePath">Path of file to move.</param>
        /// <param name="_destinationPath">Path of destination.</param>
        public static void Move(string _sourcePath, string _destinationPath)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported.");
#elif UNITY_WINRT
            Debug.LogError("[CPFileOperations] Rename Unimplemeted on windows");
#else
            File.Move(_sourcePath, _destinationPath);
#endif
        }
Ejemplo n.º 15
0
        public static void WriteAllText(string _filePath, string _contents)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported");
#elif UNITY_WINRT
            Debug.LogError("[CPFileOperations] ReadAllText Un implemeted on windows");
#else
            File.WriteAllText(_filePath, _contents);
#endif
        }
        public static void ExecuteAction(IPDFDeviceActionHandler actionHandler, IPDFDevice device, PDFAction action)
        {
            if (action != null)
            {
                PDFAction.ActionType type = action.GetActionType();

                switch (type)
                {
                case PDFAction.ActionType.Unsupported:
                    break;

                case PDFAction.ActionType.GoTo:
                    PDFDest dest = action.GetDest();
                    actionHandler.HandleGotoAction(device, dest.PageIndex);
                    break;

                case PDFAction.ActionType.RemoteGoTo:
                    string resolvedFilePath = actionHandler.HandleRemoteGotoActionPathResolving(device,
                                                                                                action.GetFilePath());

#if !((UNITY_4_6 || UNITY_4_7))
                    if (File.Exists(resolvedFilePath))
                    {
                        string password = actionHandler.HandleRemoteGotoActionPasswordResolving(device,
                                                                                                resolvedFilePath);
                        PDFDocument newDocument = new PDFDocument(resolvedFilePath, password);

                        if (newDocument.IsValid)
                        {
                            actionHandler.HandleRemoteGotoActionResolved(device, newDocument,
                                                                         action.GetDest().PageIndex);
                        }
                        else
                        {
                            actionHandler.HandleRemoteGotoActionUnresolved(device, resolvedFilePath);
                        }
                    }
                    else
#endif
                    actionHandler.HandleRemoteGotoActionUnresolved(device, resolvedFilePath);


                    break;

                case PDFAction.ActionType.Uri:
                    actionHandler.HandleUriAction(device, action.GetURIPath());
                    break;

                case PDFAction.ActionType.Launch:
                    actionHandler.HandleLaunchAction(device, action.GetFilePath());
                    break;
                }
            }
        }
Ejemplo n.º 17
0
        public bool DeleteSave()
        {
            if (!File.Exists(_saveFilePath))
            {
                return(false);
            }

            File.Delete(_saveFilePath);

            return(!File.Exists(_saveFilePath));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates or opens a file for writing UTF-8 encoded text.
        /// </summary>
        /// <param name="_filePath">The file to be opened for writing.</param>
        public static StreamWriter CreateText(string _filePath)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported");
            return(null);
#elif UNITY_WINRT
            Debug.LogError("[CPFileOperations] CreateText Un implemeted on windows");
            return(null);
#else
            return(File.CreateText(_filePath));
#endif
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Read contents of a file
        /// </summary>
        /// <param name="path">Path of the file</param>
        /// <returns>Contents of the file</returns>
        public static string Read(string path)
        {
            string result = "";

#if UNITY_WINRT && !UNITY_EDITOR
            byte[] bytes = File.ReadAllBytes(path);
            result = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
#else
            result = File.ReadAllText(path);
#endif

            return(result);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// </summary>
        /// <param name="file_path"></param>
        /// <returns></returns>
        public static Texture2D LoadPng(string file_path)
        {
            Texture2D tex = null;

            if (File.Exists(file_path))
            {
                var file_data = File.ReadAllBytes(file_path);
                tex = new Texture2D(2, 2);
                tex.LoadImage(file_data); //..this will auto-resize the texture dimensions.
            }

            return(tex);
        }
Ejemplo n.º 21
0
        public static IEnumerator Cache(CardData data)
        {
            var url = data.Image;

            if (string.IsNullOrEmpty(data.Title))
            {
                data.Title = "default";
            }

            bool   saveToFile;
            string imageName = string.Format(cachedImageNameFormat, data.Title, data.Id);
            string fileName  = Application.persistentDataPath + "/" + Path.GetFileName(imageName);

#if !UNITY_WINRT
            if (File.Exists(fileName))
            {
                saveToFile = false;
                url        = "file://" + fileName;
            }
            else
#endif
            {
                saveToFile = true;
                url        = AzureMuseumImageFormatter.GetImageUri(url, 277, 274).ToString();
            }

            WWW www = null;

            int tries = 3;
            while (--tries >= 0)
            {
                www = new WWW(url);

                yield return(www);

                if (www.bytesDownloaded != 0)
                {
                    break;
                }
            }

#if !UNITY_WINRT
            if (saveToFile && www != null && www.bytesDownloaded != 0)
            {
                fileName = Application.persistentDataPath + "/" + Path.GetFileName(imageName);
                var cache = new FileStream(fileName, FileMode.Create);
                cache.Write(www.bytes, 0, www.bytes.Length);
                cache.Close();
            }
#endif
        }
Ejemplo n.º 22
0
        public void CreateSave()
        {
            GameManager.GetEventHandler().onBeforeSave.Invoke();

            //Debug.Log(DialogueFlags.Count);
            Save save = CreateSaveGameObject();
            var  json = JsonConvert.SerializeObject(save, Formatting.Indented);

            File.WriteAllText(_saveFilePath, json);

            Debug.Log($"Saved to {_saveFilePath}");

            GameManager.GetEventHandler().onGameSaved.Invoke();
        }
Ejemplo n.º 23
0
        private void GenerateAtlasSpritePrefab(string atlasDir)
        {
            Dictionary <string, string> md5Map = new Dictionary <string, string>();

            FileInfo[] resFiles = BMEditUtility.GetAllFiles(atlasDir, "*.*");
            for (int j = 0; j < resFiles.Length; j++)
            {
                FileInfo info = resFiles[j];
                if (info.FullName.EndsWith(".meta", StringComparison.Ordinal) || info.FullName.EndsWith(".txt", StringComparison.Ordinal))
                {
                    continue;
                }

                string dirName        = Path.GetFileName(info.DirectoryName);
                string outPath        = $"{_settings.atlasSpritePrefabDir}{dirName}/";
                string spriteFileName = Path.GetFileName(info.FullName);
                string spriteName     = Path.GetFileNameWithoutExtension(info.FullName);
                string texPath        = BMEditUtility.Absolute2Relativity(info.FullName);
                string md5            = HashHelper.ComputeMD5(texPath);
                md5Map.Add(texPath, md5);
                TextureImporter ti = AssetImporter.GetAtPath(texPath) as TextureImporter;
                if (ti)
                {
                    if (!Directory.Exists(outPath))
                    {
                        Directory.CreateDirectory(outPath);
                    }
                    GameObject     spritePrefab   = new GameObject(spriteName);
                    SpriteRenderer spriteRenderer = spritePrefab.AddComponent <SpriteRenderer>();
                    Vector4        border         = ti.spriteBorder;
                    ti.spritePackingTag = "Atlas_" + dirName;
                    ti.SaveAndReimport();
                    spriteRenderer.sprite = AssetDatabase.LoadAssetAtPath <Sprite>(texPath);;
                    //spritePrefab.hideFlags = HideFlags.HideInHierarchy;
                    var savePath = outPath + spriteName + ".prefab";
                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }
                    PrefabUtility.SaveAsPrefabAsset(spritePrefab, savePath);
                    //var texture2D = AssetDatabase.LoadAssetAtPath<Texture2D>(rPath);
                    //var sprite = Sprite.Create(texture2D, new Rect(0,0,texture2D.width,texture2D.height), new Vector2(0.5f,0.5f), 400, 0,SpriteMeshType.FullRect,border);
                    DestroyImmediate(spritePrefab);
                }
            }

            //Save md5
            BMEditUtility.SaveDictionary(Path.Combine(atlasDir, "manifest.txt"), md5Map);
        }
Ejemplo n.º 24
0
        public static IEnumerator CacheAndSet(SpriteRenderer renderer, CardData data)
        {
            var url = data.Image;

            if (string.IsNullOrEmpty(data.Title))
            {
                data.Title = "default";
            }

            bool   saveToFile;
            string imageName = string.Format(cachedImageNameFormat, data.Title, data.Id);
            string fileName  = Application.persistentDataPath + "/" + Path.GetFileName(imageName);

            if (File.Exists(fileName))
            {
                saveToFile = false;
                url        = "file://" + fileName;
            }
            else
            {
                saveToFile = true;
                url        = AzureMuseumImageFormatter.GetImageUri(url, 277, 274).ToString();
            }

            var www = new WWW(url);

            yield return(www);

            if (saveToFile)
            {
                fileName = Application.persistentDataPath + "/" + Path.GetFileName(imageName);
                File.WriteAllBytes(fileName, www.bytes);
            }

            if (renderer != null)
            {
                var sprite = Sprite.Create(
                    www.texture,
                    new Rect(0, 0, 277, 274),
                    new Vector2(0.5f, 0.5f));

                renderer.sprite = sprite;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Renames a file
        /// </summary>
        /// <param name="_filePath">The file to rename.</param>
        /// <param name="_newFileName">New file name for this file.</param>
        public static void Rename(string _filePath, string _newFileName)
        {
#if (UNITY_WEBPLAYER || UNITY_WEBGL)
            Debug.LogError("[CPFileOperations] File operations are not supported.");
#elif UNITY_WINRT
            Debug.LogError("[CPFileOperations] Rename Unimplemeted on windows");
#else
            string _fileName    = Path.GetFileName(_filePath);
            string _newFilePath = _filePath.Replace(_fileName, _newFileName);

            if (File.Exists(_filePath))
            {
                if (File.Exists(_newFilePath))
                {
                    File.Delete(_newFilePath);                    //Just deleting a head incase if exists.
                }
                File.Move(_filePath, _newFilePath);
            }
#endif
        }
Ejemplo n.º 26
0
        private IEnumerator GetAppodealSDKData()
        {
            yield return(null);

            #region Internal

            if (AppodealDependencyUtils.GetInternalDependencyPath() != null)
            {
                foreach (var fileInfo in AppodealDependencyUtils.GetInternalDependencyPath())
                {
                    if (!File.Exists(AppodealDependencyUtils.Network_configs_path + fileInfo.Name))
                    {
                        AppodealDependencyUtils.ShowInternalErrorDialog(this,
                                                                        $"File doesn't exist - {AppodealDependencyUtils.Network_configs_path + fileInfo.Name}",
                                                                        string.Empty);
                    }
                    else
                    {
                        GetInternalDependencies(AppodealDependencyUtils.Network_configs_path + fileInfo.Name);
                    }
                }
            }
            else
            {
                AppodealDependencyUtils.ShowInternalErrorDialog(this,
                                                                "Can't find internal dependencies.", string.Empty);
            }

            #endregion

            #region Plugin

            var requestPlugin = UnityWebRequest.Get(AppodealDependencyUtils.PluginRequest);
            yield return(requestPlugin.Send());

            if (requestPlugin.isError)
            {
                Debug.LogError(requestPlugin.error);
                AppodealDependencyUtils.ShowInternalErrorDialog(this, requestPlugin.error, string.Empty);
            }
            else
            {
                if (string.IsNullOrEmpty(requestPlugin.downloadHandler.text))
                {
                    yield break;
                }

                if (AppodealAds.Unity.Api.Appodeal.APPODEAL_PLUGIN_VERSION.Contains("-Beta"))
                {
                    appodealUnityPlugin = JsonHelper.FromJson <AppodealUnityPlugin>(JsonHelper.fixJson(requestPlugin.downloadHandler.text))
                                          .ToList().FirstOrDefault(x => x.build_type.Equals("beta"));
                }
                else
                {
                    appodealUnityPlugin = JsonHelper.FromJson <AppodealUnityPlugin>(JsonHelper.fixJson(requestPlugin.downloadHandler.text))
                                          .ToList().FirstOrDefault(x => x.build_type.Equals("stable"));
                }
            }

            #endregion

            #region Adapters

            var requestAdapters = UnityWebRequest.Get(AppodealDependencyUtils.AdaptersRequest +
                                                      AppodealDependencyUtils.ReplaceBetaVersion(AppodealAds.Unity.Api
                                                                                                 .Appodeal.APPODEAL_PLUGIN_VERSION));

            yield return(requestAdapters.Send());

            if (requestAdapters.isError)
            {
                Debug.LogError(requestAdapters.error);
                AppodealDependencyUtils.ShowInternalErrorDialog(this, requestAdapters.error, string.Empty);
            }
            else
            {
                if (string.IsNullOrEmpty(requestAdapters.downloadHandler.text))
                {
                    yield break;
                }
                if (requestAdapters.downloadHandler.text.Contains("error"))
                {
                    AppodealDependencyUtils.ShowInternalErrorDialog(this,
                                                                    $"Can't find network configs by {AppodealAds.Unity.Api.Appodeal.APPODEAL_PLUGIN_VERSION} version",
                                                                    string.Empty);
                    yield break;
                }
                var networkDependencies = JsonHelper.FromJson <NetworkDependency>(
                    JsonHelper.fixJson(requestAdapters.downloadHandler.text));

                if (networkDependencies.Length > 0)
                {
                    foreach (var networkDependency in networkDependencies)
                    {
                        if (!string.IsNullOrEmpty(networkDependency.name) &&
                            !networkDependency.name.Equals(AppodealDependencyUtils.TwitterMoPub))
                        {
                            latestDependencies.Add(networkDependency.name, networkDependency);
                        }
                    }
                }
            }

            #endregion

            coroutine = null;

            isPluginInfoReady = true;
        }
Ejemplo n.º 27
0
 /// <summary>
 /// 路径是否存在
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns></returns>
 public static bool Exists(string fileName)
 {
     return(File.Exists(fileName));
 }
Ejemplo n.º 28
0
        public override Widget build(BuildContext context)
        {
            var stacked = new List <Widget>
            {
                new Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: new List <Widget>
                {
                    new Expanded(
                        child: new Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.only(left: 24, bottom: 2),
                            child: new EditableText(
                                globalKeyEventHandler: GlobalKeyEventHandler,
                                controller: m_TextEditingController,
                                focusNode: widget.focusNode,
                                style: new TextStyle(
                                    color: new Color(0xff000000),
                                    fontSize: 16,
                                    height: 28 / 22.4f,
                                    fontFamily: "PingFang"
                                    ),
                                selectionColor: new Color(0xff2199f4),
                                cursorColor: new Color(0xa0000000),
                                minLines: 1,
                                maxLines: 8,
                                onSubmitted: OnSubmitted,
                                backgroundCursorColor: new Color(0xffffffff)
                                )
                            )
                        ),
                    new GestureDetector(
                        onTap: () =>
                    {
                        var filePath = EditorUtility.OpenFilePanelWithFilters(
                            "",
                            "",
                            EmptyFilters);
                        if (filePath != null && filePath.isNotEmpty())
                        {
                            var rootState = HomePage.of(context);
                            var bytes     = File.ReadAllBytes(filePath);
                            var fileName  = System.IO.Path.GetFileName(filePath);
                            var ext       = System.IO.Path.GetExtension(fileName);
                            var nonce     = CreateNonce();
                            var mimeType  = GetMimeType(ext);
                            var form      = new List <IMultipartFormSection>
                            {
                                new MultipartFormDataSection("channel", rootState.SelectedChannelId),
                                new MultipartFormDataSection("nonce", nonce),
                                new MultipartFormDataSection("size", $"{bytes.Length}"),
                                new MultipartFormFileSection("file", bytes, fileName, mimeType)
                            };

                            PostForm <Models.Message>(
                                $"/api/channels/{rootState.SelectedChannelId}/messages/attachments",
                                form,
                                message => { },
                                out var progress
                                );
                            Window.NewMessages.ForEach(msg => Window.Messages[msg.channelId].Insert(0, msg));
                            Window.NewMessages.Clear();
                            setState();
                            SchedulerBinding.instance.addPostFrameCallback(value =>
                            {
                                ChattingWindow.currentState?.m_ScrollController.animateTo(
                                    0,
                                    new TimeSpan(0, 0, 0, 0, 480),
                                    Curves.easeInOut
                                    );
                            });

                            var attachment = new Attachment
                            {
                                local       = true,
                                url         = filePath,
                                contentType = mimeType,
                                progress    = progress,
                                filename    = fileName,
                                size        = bytes.Length,
                            };
                            if (mimeType.StartsWith("image/"))
                            {
                                var texture = new Texture2D(1, 1);
                                texture.LoadImage(bytes);
                                attachment.width  = texture.width;
                                attachment.height = texture.height;
                            }
                            rootState.InsertMessage(
                                rootState.SelectedChannelId,
                                new Models.Message
                            {
                                channelId   = rootState.SelectedChannelId,
                                content     = string.Empty,
                                nonce       = nonce,
                                embeds      = new List <Embed>(),
                                attachments = new List <Attachment>
                                {
                                    attachment,
                                },
                                author = widget.users[Window.currentUserId],
                            }
                                );
                        }
                    },
                        child: new Container(
                            margin: EdgeInsets.only(
                                right: 24,
                                left: 16
                                ),
                            child: new Icon(
                                IconFont.IconFontSendPic,
                                size: 28,
                                color: new Color(0xff979a9e)
                                )
                            )
                        ),
                }
Ejemplo n.º 29
0
 /// <summary>
 /// Check if the file exists
 /// </summary>
 /// <param name="path">Path of the file</param>
 /// <returns>bool</returns>
 public static bool Exists(string path)
 {
     return(File.Exists(path));
 }
Ejemplo n.º 30
0
        public override void OnInspectorGUI()
        {
            float usableWidth = Screen.width - 64f;

            serializedObject.Update();
            int       oldGridSize = (int)Mathf.Sqrt(colors.arraySize);
            int       targetCount = gridSize.intValue * gridSize.intValue;
            int       i;
            string    assetPath = AssetDatabase.GetAssetPath(serializedObject.targetObject);
            Texture2D tex       = null;

            if (oldGridSize != gridSize.intValue)
            {
                int oldArraySize     = colors.arraySize;
                int gridSizeDelta    = gridSize.intValue - oldGridSize;
                int arrayLengthDelta = targetCount - colors.arraySize;
                if (gridSizeDelta > 0)
                {
                    for (i = 0; i < targetCount; i++)
                    {
                        int y = i / gridSize.intValue;
                        int x = i % gridSize.intValue;
                        if (y > oldGridSize - 1 || x > oldGridSize - 1)
                        {
                            colors.InsertArrayElementAtIndex(i);
                            colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                        }
                    }
                }
                else if (arrayLengthDelta < 0)
                {
                    for (i = colors.arraySize - 1; i > 0; i--)
                    {
                        int y = i / oldGridSize;
                        int x = i % oldGridSize;
                        if (y > gridSize.intValue - 1 || x > gridSize.intValue - 1)
                        {
                            colors.DeleteArrayElementAtIndex(i);
                        }
                    }
                }
            }

            float cellSize = Mathf.Min(512f, usableWidth) / gridSize.intValue;

            i = 0;
            for (int y = 0; y < gridSize.intValue; y++)
            {
                EditorGUILayout.BeginHorizontal();
                for (int x = 0; x < gridSize.intValue; x++)
                {
                    SerializedProperty p = colors.GetArrayElementAtIndex(i);
                    p.colorValue = EditorGUILayout.ColorField(
                        GUIContent.none,
                        p.colorValue,
                        false,
                        true,
                        false,
                        GUILayout.Width(cellSize),
                        GUILayout.Height(cellSize)
                        );
                    i += 1;
                }
                EditorGUILayout.EndHorizontal();
            }

            GUILayout.Space(12f);

            _optionsOpen = EditorGUILayout.BeginFoldoutHeaderGroup(_optionsOpen, "Options");
            if (_optionsOpen)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(string.Format("Grid Size: {0} ({1} cells)",
                                                         gridSize.intValue,
                                                         colors.arraySize));
                GUI.enabled = gridSize.intValue > 1;
                if (GUILayout.Button("-"))
                {
                    gridSize.intValue -= 1;
                }
                GUI.enabled = gridSize.intValue < 12;  // an arbitrary choice because of the extra padding between cells
                if (GUILayout.Button("+"))
                {
                    gridSize.intValue += 1;
                }
                GUI.enabled = true;
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.PropertyField(emptyColor);
                EditorGUILayout.PropertyField(textureSize);

                GUILayout.Space(24f);
                if (GUILayout.Button("Clear Colors"))
                {
                    colors.ClearArray();
                    for (i = 0; i < targetCount; i++)
                    {
                        colors.InsertArrayElementAtIndex(i);
                        colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                    }
                }

                GUILayout.Space(12f);
            }
            EditorGUILayout.EndFoldoutHeaderGroup();

            if (tex == null)
            {
                tex = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath);
            }

            GUILayout.Space(12f);
            if (GUILayout.Button(tex == null ? "Create Texture Asset" : "Update Texture Asset"))
            {
                if (assetPath != null)
                {
                    if (colors.arraySize == 0)
                    {
                        for (i = 0; i < targetCount; i++)
                        {
                            colors.InsertArrayElementAtIndex(i);
                            colors.GetArrayElementAtIndex(i).colorValue = emptyColor.colorValue;
                        }
                    }

                    if (tex == null)
                    {
                        tex            = new Texture2D(textureSize.intValue, textureSize.intValue);
                        tex.filterMode = FilterMode.Point;
                        AssetDatabase.AddObjectToAsset(tex, assetPath);
                    }
                    tex.name = serializedObject.targetObject.name + " Texture";
                    ((ScriptableColorPalette)serializedObject.targetObject).ApplyToTexture2D(tex);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.ImportAsset(assetPath);
                }
            }

            serializedObject.ApplyModifiedProperties();

            if (tex != null)
            {
                GUILayout.Space(12f);
                GUILayout.BeginVertical(GUILayout.Width(usableWidth));
                GUILayout.Space(usableWidth);
                GUILayout.EndVertical();
                GUI.DrawTexture(GUILayoutUtility.GetLastRect(), tex);

                GUILayout.Space(12f);
                GUILayout.Label(tex.name);
                GUILayout.Label(string.Format("{0}px by {1}px", tex.width, tex.height));

                GUILayout.Space(12f);
                if (GUILayout.Button("Show in Project"))
                {
                    EditorGUIUtility.PingObject(tex);
                }

                if (GUILayout.Button("Export PNG"))
                {
                    string savePath = EditorUtility.SaveFilePanel(
                        string.Format("Export {0} as PNG", tex.name),
                        "",
                        string.Format("{0}.png", tex.name),
                        "png"
                        );

                    if (savePath.Length != 0)
                    {
                        var pngData = tex.EncodeToPNG();
                        if (pngData != null)
                        {
                            File.WriteAllBytes(savePath, pngData);
                        }
                    }
                }
            }
        }