Example #1
0
        public void Backup(string file)
        {
            if (!SdeAppConfiguration.BackupsManagerState || !IsStarted || _backupThread.IsCrashed)
            {
                return;
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            try {
                string relativePath = file.ReplaceFirst(GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath) + IOHelper.Slash, "");

                if (String.IsNullOrEmpty(relativePath))
                {
                    return;
                }

                _validateOpened();

                string fullPath = GrfPath.Combine(_paths[_currentId], relativePath);
                string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}");
                IOHelper.Copy(file, tempFile);

                _localToGrfPath[_currentId][tempFile] = fullPath;
            }
            catch {
            }
        }
Example #2
0
        private CmdInfo _generateMissingCmd(string icon, string displayName, string sdeResource, Func <ValidationErrorView, bool> canExecute)
        {
            return(new CmdInfo {
                CmdName = displayName,
                Icon = icon,
                DisplayName = displayName,
                CanExecute = canExecute,
                _execute = t => {
                    var cpy = sdeResource;

                    if (String.IsNullOrEmpty(cpy.GetExtension()))
                    {
                        cpy = cpy + ((ResourceError)t).MissingPath.GetExtension();
                    }

                    var path = GrfPath.Combine(SdeAppConfiguration.TempPath, cpy);

                    if (!File.Exists(path))
                    {
                        File.WriteAllBytes(path, ApplicationManager.GetResource(cpy));
                    }

                    ValidationEngine.Grf.Commands.AddFileAbsolute(((ResourceError)t).MissingPath.ToDisplayEncoding(), path);
                    return true;
                }
            });
        }
Example #3
0
        public void BackupClient(string file, byte[] data)
        {
            if (!SdeAppConfiguration.BackupsManagerState || !IsStarted || _backupThread.IsCrashed)
            {
                return;
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (data == null)
            {
                return;
            }

            try {
                string relativePath = GrfPath.Combine("client", Path.GetFileName(file));                 //.ReplaceFirst(GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath) + (isFtp ? "/" : "\\"), "");

                if (String.IsNullOrEmpty(relativePath))
                {
                    return;
                }

                _validateOpened();

                string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}");
                File.WriteAllBytes(tempFile, data);

                string fullPath = GrfPath.Combine(_paths[_currentId], relativePath);
                _localToGrfPath[_currentId][tempFile] = fullPath;
            }
            catch {
            }
        }
Example #4
0
        /// <summary>
        /// Exports the specified folder from the GRF.
        /// </summary>
        /// <param name="folder">The extraction folder path.</param>
        /// <param name="backup">The backup path.</param>
        /// <exception cref="ArgumentNullException">
        /// folder
        /// or
        /// backup
        /// </exception>
        public void Export(string folder, string backup)
        {
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }
            if (backup == null)
            {
                throw new ArgumentNullException("backup");
            }

            _validateOpened();

            foreach (FileEntry entry in _grf.FileTable.EntriesInDirectory(backup, SearchOption.AllDirectories))
            {
                if (entry.RelativePath.EndsWith(InfoName))
                {
                    continue;
                }

                entry.ExtractFromAbsolute(GrfPath.Combine(folder, entry.RelativePath.ReplaceFirst(backup + "\\", "")));
            }

            _grf.Close();
        }
Example #5
0
        public void Backup(string file)
        {
            if (!SdeAppConfiguration.BackupsManagerState || !_isStarted || _isCrashed)
            {
                return;
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            try {
                string relativePath = file.ReplaceFirst(GrfPath.GetDirectoryName(SdeFiles.ServerDbPath) + "\\", "");

                if (String.IsNullOrEmpty(relativePath))
                {
                    return;
                }

                _validateOpened();

                if (!_paths.ContainsKey(_currentId))
                {
                    _paths[_currentId] = _getGrfPath();
                }

                string fullPath = GrfPath.Combine(_paths[_currentId], relativePath);
                string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}");
                File.Copy(file, tempFile);

                _grf.Commands.AddFileAbsolute(fullPath, tempFile);
            }
            catch { }
        }
Example #6
0
        /// <summary>
        /// Restores the specified backup.
        /// </summary>
        /// <param name="backup">The backup path.</param>
        /// <exception cref="ArgumentNullException">backup</exception>
        public void Restore(string backup)
        {
            if (backup == null)
            {
                throw new ArgumentNullException("backup");
            }

            _validateOpened();

            BackupInfo info = new BackupInfo(new ReadonlyConfigAsker(_grf.FileTable[GrfPath.Combine(backup, InfoName)].GetDecompressedData()));

            if (!Directory.Exists(info.DestinationPath))
            {
                Directory.CreateDirectory(info.DestinationPath);
            }

            foreach (FileEntry entry in _grf.FileTable.EntriesInDirectory(backup, SearchOption.AllDirectories))
            {
                if (entry.RelativePath.EndsWith(InfoName))
                {
                    continue;
                }

                entry.ExtractFromAbsolute(GrfPath.Combine(info.DestinationPath, entry.RelativePath.ReplaceFirst(backup + "\\", "")));
            }

            _grf.Close();
        }
Example #7
0
        public SftpDb(string path)
        {
            DestPath = GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, path.GetHashCode().ToString(CultureInfo.InvariantCulture));
            var file = GrfPath.Combine(DestPath, "files.dat");

            GrfPath.CreateDirectoryFromFile(file);
            _config = new ConfigAsker(file);
        }
Example #8
0
 public App()
 {
     Configuration.ConfigAsker        = SdeAppConfiguration.ConfigAsker;
     ProjectConfiguration.ConfigAsker = SdeAppConfiguration.ConfigAsker;
     Settings.TempPath = GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp\\" + SdeAppConfiguration.ProcessId);
     ErrorHandler.SetErrorHandler(new DefaultErrorHandler());
     ClearTemporaryFiles();
 }
Example #9
0
 public App()
 {
     Configuration.ConfigAsker        = SdeAppConfiguration.ConfigAsker;
     ProjectConfiguration.ConfigAsker = SdeAppConfiguration.ConfigAsker;
     Settings.TempPath = GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp");
     ErrorHandler.SetErrorHandler(new SdeErrorHandler());
     TemporaryFilesManager.ClearTemporaryFiles();
 }
Example #10
0
        public SettingsDialog() : base("Advanced settings", "settings.png")
        {
            InitializeComponent();
            int row;

            Binder.Bind(_pbNotepad.TextBox, () => SdeAppConfiguration.NotepadPath);

            _add(_gridComments, row = 0, "Add comments in item_trade.txt", "Displays the item name as a comment at the end of the line for item_trade.txt.", () => SdeAppConfiguration.AddCommentForItemTrade, v => SdeAppConfiguration.AddCommentForItemTrade = v);
            _add(_gridComments, ++row, "Add comments in item_avail.txt", "Displays the item names as a comment at the end of the line for item_avail.txt.", () => SdeAppConfiguration.AddCommentForItemAvail, v => SdeAppConfiguration.AddCommentForItemAvail = v);
            _add(_gridComments, ++row, "Add comments in item_nouse.txt", "Displays the item names as a comment at the end of the line for item_nouse.txt.", () => SdeAppConfiguration.AddCommentForItemNoUse, v => SdeAppConfiguration.AddCommentForItemNoUse = v);

            _add(_gridGeneral, row = 3, "Switch item types 4 and 5 for text based databases (requires a software restart)", "Switches the armor and weapon types when reading the databases.", () => SdeAppConfiguration.RevertItemTypes, v => SdeAppConfiguration.RevertItemTypes = v);
            _add(_gridGeneral, ++row, "Always reopen the latest opened project", "Always reopen the most recently opened project when starting the application.", () => SdeAppConfiguration.AlwaysReopenLatestProject, v => SdeAppConfiguration.AlwaysReopenLatestProject = v);
            _add(_gridGeneral, ++row, "Associate the .sde file extension with this tool", null, () => (SdeAppConfiguration.FileShellAssociated & FileAssociation.Sde) == FileAssociation.Sde, v => {
                if (v)
                {
                    SdeAppConfiguration.FileShellAssociated |= FileAssociation.Sde;
                    ApplicationManager.AddExtension(Methods.ApplicationFullPath, "Server database editor", ".sde", true);
                }
                else
                {
                    SdeAppConfiguration.FileShellAssociated &= ~FileAssociation.Sde;
                    GrfPath.Delete(GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "sde.ico"));
                    ApplicationManager.RemoveExtension(Methods.ApplicationFullPath, ".sde");
                }
            });
            _add(_gridGeneral, ++row, "Enable backups manager", null, () => SdeAppConfiguration.BackupsManagerState, v => SdeAppConfiguration.BackupsManagerState = v);
            _add(_gridGeneral, ++row, "Apply modifications to all selected items", "If checked, every field that you edit will modify all the currently selected items.", () => SdeAppConfiguration.EnableMultipleSetters, v => SdeAppConfiguration.EnableMultipleSetters = v);
            _add(_gridGeneral, ++row, "Bind item tabs together", "If checked, both the Client Items and Items tab will sync.", () => SdeAppConfiguration.BindItemTabs, v => SdeAppConfiguration.BindItemTabs = v);
            _add(_gridGeneral, ++row, "Always overwrite non-modified files", "If checked, non-modified files will be overwritten in your db folder.", () => SdeAppConfiguration.AlwaysOverwriteFiles, v => SdeAppConfiguration.AlwaysOverwriteFiles = v);

            _add(_gridDbWriter, row = 0, "Remove NoUse entry if the flag is 0 (ignore override)", "This will remove the line regardless of the override property, which must be normally at 100 for the line to be removed.", () => SdeAppConfiguration.DbNouseIgnoreOverride, v => SdeAppConfiguration.DbNouseIgnoreOverride = v);
            _add(_gridDbWriter, ++row, "Remove Trade entry if the flag is 0 (ignore override)", "This will remove the line regardless of the override property, which must be normally at 100 for the line to be removed.", () => SdeAppConfiguration.DbTradeIgnoreOverride, v => SdeAppConfiguration.DbTradeIgnoreOverride = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write unidentifiedDisplayName", null, () => SdeAppConfiguration.DbWriterItemInfoUnDisplayName, v => SdeAppConfiguration.DbWriterItemInfoUnDisplayName     = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write unidentifiedResourceName", null, () => SdeAppConfiguration.DbWriterItemInfoUnResource, v => SdeAppConfiguration.DbWriterItemInfoUnResource          = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write unidentifiedDescriptionName", null, () => SdeAppConfiguration.DbWriterItemInfoUnDescription, v => SdeAppConfiguration.DbWriterItemInfoUnDescription = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write identifiedDisplayName", null, () => SdeAppConfiguration.DbWriterItemInfoIdDisplayName, v => SdeAppConfiguration.DbWriterItemInfoIdDisplayName       = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write identifiedResourceName", null, () => SdeAppConfiguration.DbWriterItemInfoIdResource, v => SdeAppConfiguration.DbWriterItemInfoIdResource            = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write identifiedDescriptionName", null, () => SdeAppConfiguration.DbWriterItemInfoIdDescription, v => SdeAppConfiguration.DbWriterItemInfoIdDescription   = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write slotCount", null, () => SdeAppConfiguration.DbWriterItemInfoSlotCount, v => SdeAppConfiguration.DbWriterItemInfoSlotCount = v);
            _add(_gridDbWriter, ++row, "itemInfo.lua : Write ClassNum", null, () => SdeAppConfiguration.DbWriterItemInfoClassNum, v => SdeAppConfiguration.DbWriterItemInfoClassNum    = v);
            _add(_gridDbWriter, ++row, "item_group : force write in single file", "'Import' fields won't be used when saving the item groups", () => SdeAppConfiguration.DbWriterItemInfoClassNum, v => SdeAppConfiguration.DbWriterItemInfoClassNum = v);

            _add(_gridDialogs, row = 0, "Use integrated dialogs for flags", "If unchecked, this will open dialogs on all the '...' buttons.", () => SdeAppConfiguration.UseIntegratedDialogsForFlags, v => SdeAppConfiguration.UseIntegratedDialogsForFlags = v);
            _add(_gridDialogs, ++row, "Use integrated dialogs for scripts", "If unchecked, this will open dialogs on all the '...' buttons.", () => SdeAppConfiguration.UseIntegratedDialogsForScripts, v => SdeAppConfiguration.UseIntegratedDialogsForScripts = v);
            _add(_gridDialogs, ++row, "Use integrated dialogs for levels", "If unchecked, this will open dialogs on all the '...' buttons.", () => SdeAppConfiguration.UseIntegratedDialogsForLevels, v => SdeAppConfiguration.UseIntegratedDialogsForLevels    = v);
            _add(_gridDialogs, ++row, "Use integrated dialogs for jobs", "If unchecked, this will open dialogs on all the '...' buttons.", () => SdeAppConfiguration.UseIntegratedDialogsForJobs, v => SdeAppConfiguration.UseIntegratedDialogsForJobs          = v);
            _add(_gridDialogs, ++row, "Use integrated dialogs for time", "If unchecked, this will open dialogs on all the '...' buttons.", () => SdeAppConfiguration.UseIntegratedDialogsForTime, v => SdeAppConfiguration.UseIntegratedDialogsForTime          = v);

            _add(_gridRAthena, row = 0, "Use old rAthena mob mode", "If checked, this will use the old mob mode.", () => ProjectConfiguration.UseOldRAthenaMode, v => ProjectConfiguration.UseOldRAthenaMode = v);

            _loadEncoding();
            _comboBoxCompression.Init();
            _loadAutocomplete();
            _loadShortcuts();
        }
        private Dictionary <int, int> _getWeaponClasses()
        {
            Dictionary <int, int> table = new Dictionary <int, int>();
            var accIdPath = ProjectConfiguration.SyncAccId;

            for (int i = 0; i <= 30; i++)
            {
                table[i] = i;
            }

            if (_database.MetaGrf.GetData(ProjectConfiguration.SyncAccId) == null || _database.MetaGrf.GetData(ProjectConfiguration.SyncAccName) == null)
            {
                return(table);
            }

            var weaponPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "weapontable" + Path.GetExtension(accIdPath));
            var weaponData = _database.MetaGrf.GetData(weaponPath);

            if (weaponData == null)
            {
                return(table);
            }

            var weaponTable = new LuaParser(weaponData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(weaponData), EncodingService.DisplayEncoding);
            var weaponIds   = LuaHelper.GetLuaTable(weaponTable, "Weapon_IDs");
            var weaponExpansionNameTable = LuaHelper.GetLuaTable(weaponTable, "Expansion_Weapon_IDs");

            var ids = LuaHelper.SetIds(weaponIds, "Weapon_IDs");

            foreach (var id in ids)
            {
                if (id.Value == 24)
                {
                    continue;
                }

                if (id.Value <= 30)
                {
                    table[id.Value] = id.Value;
                }
                else
                {
                    string sval;
                    if (weaponExpansionNameTable.TryGetValue("[" + id.Key + "]", out sval))
                    {
                        int ival;
                        if (ids.TryGetValue(sval, out ival))
                        {
                            table[id.Value] = ival;
                        }
                    }
                }
            }

            return(table);
        }
Example #12
0
        public Backup(string backup)
        {
            if (backup == null)
            {
                throw new ArgumentNullException("backup");
            }

            BackupDate = backup;
            Entry      = BackupEngine.Instance.Grf.FileTable[GrfPath.Combine(BackupDate, BackupEngine.InfoName)];
            Info       = new BackupInfo(new ReadonlyConfigAsker(Entry.GetDecompressedData()));
        }
 private void _buttonOk_Click(object sender, RoutedEventArgs e)
 {
     try {
         string t;
         CurrentPath  = GrfPath.Combine(_currentPath, _listViewResults.SelectedItem != null ? ((t = ((FtpEntry)_listViewResults.SelectedItem).Name) == ".." ? "" : t) : "").Replace("\\", "/");
         DialogResult = true;
         Close();
     }
     catch (Exception err) {
         ErrorHandler.HandleException(err);
     }
 }
        private void _buttonExport_Click(object sender, RoutedEventArgs e)
        {
            try {
                var tuple = ViewIdPreviewDialog.LatestTupe;

                if (tuple == null)
                {
                    return;
                }

                var sprite = LuaHelper.GetSpriteFromViewId(tuple.GetIntNoThrow(ServerItemAttributes.ClassNumber), LuaHelper.ViewIdTypes.Headgear, SdeEditor.Instance.ProjectDatabase.GetDb <int>(ServerDbs.Items), tuple);

                string[] files = new string[] {
                    @"data\sprite\¾ÆÀÌÅÛ\" + sprite + ".spr",
                    @"data\sprite\¾ÆÀÌÅÛ\" + sprite + ".act",
                    @"data\sprite\¾Ç¼¼»ç¸®\³²\³²_" + sprite + ".spr",
                    @"data\sprite\¾Ç¼¼»ç¸®\³²\³²_" + sprite + ".act",
                    @"data\sprite\¾Ç¼¼»ç¸®\¿©\¿©_" + sprite + ".spr",
                    @"data\sprite\¾Ç¼¼»ç¸®\¿©\¿©_" + sprite + ".act",
                    @"data\texture\À¯ÀúÀÎÅÍÆäÀ̽º\collection\" + sprite + ".bmp",
                    @"data\texture\À¯ÀúÀÎÅÍÆäÀ̽º\item\" + sprite + ".bmp"
                };

                string path = PathRequest.FolderEditor();

                if (path == null)
                {
                    return;
                }

                var grf = SdeEditor.Instance.ProjectDatabase.MetaGrf;

                foreach (var file in files)
                {
                    var data = grf.GetData(file);

                    if (data != null)
                    {
                        string subPath = GrfPath.Combine(path, file);
                        GrfPath.CreateDirectoryFromFile(subPath);
                        File.WriteAllBytes(subPath, data);
                    }
                }

                OpeningService.OpenFolder(path);
            }
            catch (Exception err) {
                ErrorHandler.HandleException(err);
            }
        }
Example #15
0
        /// <summary>
        /// Clears the temporary files, this method is different than GRFE's (and it is better).
        /// </summary>
        public static void ClearTemporaryFiles()
        {
            GrfThread.Start(delegate {
                int errorCount = 0;

                // Clear root files only
                if (Directory.Exists(GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp")))
                {
                    foreach (string file in Directory.GetFiles(GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp"), "*", SearchOption.TopDirectoryOnly))
                    {
                        if (!GrfPath.Delete(file))
                        {
                            errorCount++;
                        }

                        if (errorCount > 20)
                        {
                            break;
                        }
                    }

                    // There will be no files in the temporary folder anymore
                    foreach (var directory in Directory.GetDirectories(GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp"), "*"))
                    {
                        string folderName = Path.GetFileName(directory);
                        int processId;

                        if (Int32.TryParse(folderName, out processId))
                        {
                            try {
                                Process.GetProcessById(processId);
                                // Do not bother if the process exists, even if it's not SDE
                            }
                            catch (ArgumentException) {
                                // The process is not running
                                try {
                                    Directory.Delete(directory, true);
                                }
                                catch { }
                            }
                            catch {
                                // Do nothing
                            }
                        }
                    }
                }
            }, "GRF - TemporaryFilesManager cleanup");
        }
Example #16
0
        public App()
        {
            Configuration.ConfigAsker = MapcacheConfiguration.ConfigAsker;
            Settings.TempPath         = GrfPath.Combine(MapcacheConfiguration.ProgramDataPath, "~tmp\\" + MapcacheConfiguration.ProcessId);
            ErrorHandler.SetErrorHandler(new DefaultErrorHandler());

            if (!Directory.Exists(Settings.TempPath))
            {
                try {
                    GrfPath.CreateDirectoryFromFile(Settings.TempPath);
                }
                catch {
                }
            }

            ClearTemporaryFiles();
        }
Example #17
0
        private void _save(string path = null)
        {
            _async.SetAndRunOperation(new GrfThread(delegate {
                try {
                    Progress = -1;

                    LuaParser accId = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding);
                    Dictionary <string, string> accIdT = new Dictionary <string, string>();
                    accId.Tables["ACCESSORY_IDs"]      = accIdT;

                    LuaParser accName = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding);
                    Dictionary <string, string> accNameT = new Dictionary <string, string>();
                    accName.Tables["AccNameTable"]       = accNameT;

                    foreach (var item in _obItems.Where(item => item.Id > 0).Where(item => !String.IsNullOrEmpty(item.AccId)))
                    {
                        accIdT[item.AccId] = item.Id.ToString(CultureInfo.InvariantCulture);
                    }

                    if (path == null)
                    {
                        _multiGrf.Clear();
                        string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua");
                        _writeAccName(file, EncodingService.DisplayEncoding);
                        _multiGrf.SetData(ProjectConfiguration.SyncAccName, File.ReadAllBytes(file));

                        file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua");
                        accId.Write(file, EncodingService.DisplayEncoding);
                        _multiGrf.SetData(ProjectConfiguration.SyncAccId, File.ReadAllBytes(file));
                        _multiGrf.SaveAndReload();
                    }
                    else
                    {
                        Directory.CreateDirectory(path);
                        _writeAccName(GrfPath.Combine(path, "accname.lub"), EncodingService.DisplayEncoding);
                        accId.Write(GrfPath.Combine(path, "accessoryid.lub"), EncodingService.DisplayEncoding);
                    }
                }
                catch (Exception err) {
                    ErrorHandler.HandleException(err);
                }
                finally {
                    Progress = 100f;
                }
            }, this, 200));
        }
Example #18
0
        /// <summary>
        /// Goes up in the parent folder until the path is found.
        /// </summary>
        /// <param name="db">The sub path to find.</param>
        /// <returns>The path found.</returns>
        public static string DetectPathAll(string db)
        {
            try {
                string path = SdeFiles.ServerDbPath.Filename;

                while (path != null)
                {
                    if (File.Exists(GrfPath.Combine(path, db)))
                    {
                        return(GrfPath.Combine(path, db));
                    }

                    path = Path.GetDirectoryName(path);
                }

                return(null);
            }
            catch {
                return(null);
            }
        }
Example #19
0
        /// <summary>
        /// Goes up in the parent folder until the path is found.
        /// </summary>
        /// <param name="db">The sub path to find.</param>
        /// <returns>The path found.</returns>
        public static string DetectPathAll(string db)
        {
            try {
                string path = ProjectConfiguration.DatabasePath;

                while (path != null)
                {
                    if (FtpHelper.Exists(GrfPath.Combine(path, db)))
                    {
                        return(GrfPath.Combine(path, db));
                    }

                    path = GrfPath.GetDirectoryName(path);
                }

                return(null);
            }
            catch {
                return(null);
            }
        }
Example #20
0
        public void Start(string dbPath)
        {
            if (!SdeAppConfiguration.BackupsManagerState || _isCrashed)
            {
                return;
            }
            if (dbPath == null)
            {
                throw new ArgumentNullException("dbPath");
            }

            _currentId++;

            _validateOpened();

            BackupInfo info = new BackupInfo(new TextConfigAsker(new byte[] {}));

            info.DestinationPath = Path.GetDirectoryName(dbPath);

            if (!_paths.ContainsKey(_currentId))
            {
                _paths[_currentId] = _getGrfPath();
            }

            _grf.Commands.AddFileAbsolute(GrfPath.Combine(_paths[_currentId], InfoName), info.GetData());

            List <string> paths = GetBackupFiles().OrderBy(long.Parse).ToList();

            while (paths.Count > MaximumNumberOfBackups)
            {
                RemoveBackupDelayed(paths[0]);
                paths.RemoveAt(0);
            }

            _isStarted = true;
        }
        private void _update()
        {
            string t;

            _label.Dispatch(p => p.Content = "Path: " + GrfPath.Combine(_currentPath, _listViewResults.SelectedItem != null ? ((t = ((FtpEntry)_listViewResults.SelectedItem).Name) == ".." ? "" : t) : "").Replace("\\", "/"));
        }
Example #22
0
        public static bool GetIdToSpriteTable(AbstractDb <int> db, ViewIdTypes type, out Dictionary <int, string> outputIdsToSprites, out string error)
        {
            outputIdsToSprites = new Dictionary <int, string>();
            error = null;

            if (db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId) == null || db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName) == null)
            {
                error = "The accessory ID table or accessory name table has not been set, the paths are based on those.";
                return(false);
            }

            int    temp_i;
            string temp_s;
            var    accIdPath = ProjectConfiguration.SyncAccId;
            Dictionary <string, int> ids;

            switch (type)
            {
            case ViewIdTypes.Weapon:
                if (_weaponBuffer.IsBuffered())
                {
                    outputIdsToSprites = _weaponBuffer.Ids;
                    error = _weaponBuffer.Error;
                    return(_weaponBuffer.Result);
                }

                var weaponPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "weapontable" + Path.GetExtension(accIdPath));
                var weaponData = db.ProjectDatabase.MetaGrf.GetData(weaponPath);

                if (weaponData == null)
                {
                    error = "Couldn't find " + weaponPath;
                    _weaponBuffer.Buffer(outputIdsToSprites, false, error);
                    return(false);
                }

                var weaponTable     = new LuaParser(weaponData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(weaponData), EncodingService.DisplayEncoding);
                var weaponIds       = GetLuaTable(weaponTable, "Weapon_IDs");
                var weaponNameTable = GetLuaTable(weaponTable, "WeaponNameTable");

                ids = SetIds(weaponIds, "Weapon_IDs");

                foreach (var pair in weaponNameTable)
                {
                    temp_s = pair.Key.Trim('[', ']');

                    if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i))
                    {
                        outputIdsToSprites[temp_i] = pair.Value.Trim('\"');
                    }
                }

                _weaponBuffer.Buffer(outputIdsToSprites, true, null);
                return(true);

            case ViewIdTypes.Npc:
                if (_npcBuffer.IsBuffered())
                {
                    outputIdsToSprites = _npcBuffer.Ids;
                    error = _npcBuffer.Error;
                    return(_npcBuffer.Result);
                }

                var npcPathSprites = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "jobname" + Path.GetExtension(accIdPath));
                var npcPathIds     = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "npcIdentity" + Path.GetExtension(accIdPath));
                var npcDataSprites = db.ProjectDatabase.MetaGrf.GetData(npcPathSprites);
                var npcDataIds     = db.ProjectDatabase.MetaGrf.GetData(npcPathIds);

                if (npcDataSprites == null)
                {
                    error = "Couldn't find " + npcPathSprites;
                    _npcBuffer.Buffer(outputIdsToSprites, false, error);
                    return(false);
                }

                if (npcDataIds == null)
                {
                    error = "Couldn't find " + npcPathIds;
                    _npcBuffer.Buffer(outputIdsToSprites, false, error);
                    return(false);
                }

                //var itemDb = db.GetMeta<int>(ServerDbs.Items);
                var jobname = new LuaParser(npcDataSprites, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(npcDataSprites), EncodingService.DisplayEncoding);
                var jobtbl  = new LuaParser(npcDataIds, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(npcDataIds), EncodingService.DisplayEncoding);

                var jobtblT  = GetLuaTable(jobtbl, "jobtbl");
                var jobnameT = GetLuaTable(jobname, "JobNameTable");

                ids = SetIds(jobtblT, "jobtbl");

                foreach (var pair in jobnameT)
                {
                    temp_s = pair.Key.Trim('[', ']');

                    if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i))
                    {
                        outputIdsToSprites[temp_i] = pair.Value.Trim('\"');
                    }
                }

                _npcBuffer.Buffer(outputIdsToSprites, true, null);
                return(true);

            case ViewIdTypes.Headgear:
                if (_headgearBuffer.IsBuffered())
                {
                    outputIdsToSprites = _headgearBuffer.Ids;
                    error = _headgearBuffer.Error;
                    return(_headgearBuffer.Result);
                }

                var redirectionTable = GetRedirectionTable();
                var dataAccId        = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId);
                var dataAccName      = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName);
                var itemDb           = db.GetMeta <int>(ServerDbs.Items);
                var accId            = new LuaParser(dataAccId, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccId), EncodingService.DisplayEncoding);
                var accName          = new LuaParser(dataAccName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccName), EncodingService.DisplayEncoding);
                var accIdT           = GetLuaTable(accId, "ACCESSORY_IDs");
                var accNameT         = GetLuaTable(accName, "AccNameTable");
                outputIdsToSprites = _getViewIdTable(accIdT, accNameT);

                accIdT.Clear();
                accNameT.Clear();

                var resourceToIds = new Dictionary <string, int>();

                if (ProjectConfiguration.HandleViewIds)
                {
                    try {
                        List <ReadableTuple <int> > headgears = itemDb.FastItems.Where(p => ItemParser.IsArmorType(p) && (p.GetIntNoThrow(ServerItemAttributes.Location) & 7937) != 0).OrderBy(p => p.GetIntNoThrow(ServerItemAttributes.ClassNumber)).ToList();
                        _loadFallbackValues(outputIdsToSprites, headgears, accIdT, accNameT, resourceToIds, redirectionTable);
                    }
                    catch (Exception err) {
                        error = err.ToString();
                        _headgearBuffer.Buffer(outputIdsToSprites, false, error);
                        return(false);
                    }
                }

                _headgearBuffer.Buffer(outputIdsToSprites, true, null);
                return(true);

            case ViewIdTypes.Shield:
                if (_shieldBuffer.IsBuffered())
                {
                    outputIdsToSprites = _shieldBuffer.Ids;
                    error = _shieldBuffer.Error;
                    return(_shieldBuffer.Result);
                }

                var shieldPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "ShieldTable" + Path.GetExtension(accIdPath));
                var shieldData = db.ProjectDatabase.MetaGrf.GetData(shieldPath);

                if (shieldData == null)
                {
                    outputIdsToSprites[1] = "_°¡µå";
                    outputIdsToSprites[2] = "_¹öŬ·¯";
                    outputIdsToSprites[3] = "_½¯µå";
                    outputIdsToSprites[4] = "_¹Ì·¯½¯µå";
                    outputIdsToSprites[5] = "";
                    outputIdsToSprites[6] = "";
                }
                else
                {
                    _debugStatus = "OK";

                    var shieldTable = new LuaParser(shieldData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(shieldData), EncodingService.DisplayEncoding);

                    _debugStatus = "LoadTables";

                    var shieldIds       = GetLuaTable(shieldTable, "Shield_IDs");
                    var shieldNameTable = GetLuaTable(shieldTable, "ShieldNameTable");
                    var shieldMapTable  = GetLuaTable(shieldTable, "ShieldMapTable");

                    ids = SetIds(shieldIds, "Shield_IDs");
                    Dictionary <int, string> idsToSprite = new Dictionary <int, string>();

                    foreach (var pair in shieldNameTable)
                    {
                        temp_s = pair.Key.Trim('[', ']');

                        if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i))
                        {
                            temp_s = pair.Value.Trim('\"');
                            idsToSprite[temp_i]        = temp_s;
                            outputIdsToSprites[temp_i] = temp_s;
                        }
                    }

                    foreach (var pair in shieldMapTable)
                    {
                        var key = pair.Key.Trim('[', ']', '\t');
                        int id1;

                        if (ids.TryGetValue(key, out id1))
                        {
                            int id2;
                            temp_s = pair.Value.Trim('\"', '\t');

                            if (ids.TryGetValue(temp_s, out id2) || Int32.TryParse(temp_s, out id2))
                            {
                                if (idsToSprite.TryGetValue(id2, out temp_s))
                                {
                                    outputIdsToSprites[id1] = temp_s;
                                }
                            }
                        }
                    }

                    error = PreviewHelper.ViewIdIncrease;
                }

                _shieldBuffer.Buffer(outputIdsToSprites, true, error);
                return(true);

            case ViewIdTypes.Garment:
                if (_garmentBuffer.IsBuffered())
                {
                    outputIdsToSprites = _garmentBuffer.Ids;
                    error = _garmentBuffer.Error;
                    return(_garmentBuffer.Result);
                }

                var robeSpriteName = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "spriterobename" + Path.GetExtension(accIdPath));
                var robeSpriteId   = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "spriterobeid" + Path.GetExtension(accIdPath));
                var robeNameData   = db.ProjectDatabase.MetaGrf.GetData(robeSpriteName);
                var robeIdData     = db.ProjectDatabase.MetaGrf.GetData(robeSpriteId);

                if (robeNameData == null)
                {
                    error = "Couldn't find " + robeSpriteName;
                    _garmentBuffer.Buffer(outputIdsToSprites, false, error);
                    return(false);
                }

                if (robeIdData == null)
                {
                    error = "Couldn't find " + robeSpriteId;
                    _garmentBuffer.Buffer(outputIdsToSprites, false, error);
                    return(false);
                }

                var robeNameTable = new LuaParser(robeNameData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(robeNameData), EncodingService.DisplayEncoding);
                var robeIdTable   = new LuaParser(robeIdData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(robeIdData), EncodingService.DisplayEncoding);
                var robeNames     = GetLuaTable(robeNameTable, "RobeNameTable");
                var robeIds       = GetLuaTable(robeIdTable, "SPRITE_ROBE_IDs");

                ids = SetIds(robeIds, "SPRITE_ROBE_IDs");

                foreach (var pair in robeNames)
                {
                    temp_s = pair.Key.Trim('[', ']');

                    if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i))
                    {
                        outputIdsToSprites[temp_i] = pair.Value.Trim('\"');
                    }
                }

                _garmentBuffer.Buffer(outputIdsToSprites, true, null);
                return(true);
            }

            return(false);
        }
Example #23
0
        private void _threadStart(object sender, TextChangedEventArgs e)
        {
            try {
                var    text  = _textBox.Text;
                var    tuple = e == null ? sender as ReadableTuple <int> : _tab._listView.SelectedItem as ReadableTuple <int>;
                byte[] data  = _tab.ProjectDatabase.MetaGrf.GetData(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath, text) + _ext));

                if (tuple != null)
                {
                    if (e != null)
                    {
                        _redirect = tuple.GetIntNoThrow(ServerMobAttributes.Sprite);
                    }

                    if (_redirect > 0)
                    {
                        var db = _tab.GetMetaTable <int>(ServerDbs.Mobs);
                        tuple     = db.TryGetTuple(_redirect);
                        _redirect = 0;

                        if (tuple != null)
                        {
                            var val = tuple.GetValue <string>(ServerMobAttributes.ClientSprite);
                            data = _tab.ProjectDatabase.MetaGrf.GetData(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath, val) + _ext));
                        }
                    }
                }

                if (data != null)
                {
                    if (_ext == ".spr")
                    {
                        try {
                            var image = Spr.GetFirstImage(data);

                            if (image != null)
                            {
                                _wrapper.Image = image;
                                _wrapper.Image.MakePinkTransparent();
                                _wrapper.Image.MakeFirstPixelTransparent();

                                _image.BeginDispatch(delegate {
                                    var bitmap    = _wrapper.Image.Cast <BitmapSource>();
                                    _image.Tag    = text;
                                    _image.Source = bitmap;
                                });
                            }
                            else
                            {
                                _cancelImage();
                            }
                        }
                        catch {
                            _cancelImage();
                        }
                    }
                    else
                    {
                        _wrapper.Image = ImageProvider.GetImage(data, _ext);
                        _wrapper.Image.MakePinkTransparent();
                        _wrapper.Image.MakeFirstPixelTransparent();

                        _image.BeginDispatch(delegate {
                            var bitmap    = _wrapper.Image.Cast <BitmapSource>();
                            _image.Tag    = text;
                            _image.Source = bitmap;
                        });
                    }
                }
                else
                {
                    _cancelImage();
                }
            }
            catch (Exception err) {
                _cancelImage();
                ErrorHandler.HandleException(err);
            }
        }
Example #24
0
        public void _start()
        {
            try {
                while (true)
                {
                    Pause();

                    var keys = _pendingBackups.Keys.ToList();

                    foreach (var key in keys.Where(p => p > _backupId).OrderBy(p => p))
                    {
                        string grfPath = GrfPath.Combine(Settings.TempPath, "backup_" + _backupId + ".grf");

                        using (GrfHolder grf = new GrfHolder(grfPath, GrfLoadOptions.New)) {
                            foreach (var entry in _pendingBackups[key])
                            {
                                grf.Commands.AddFileAbsolute(entry.Value, entry.Key);
                            }

                            grf.Save();
                            grf.Reload();

                            // Currently saving another file, stop before breaking anything
                            if (BackupEngine.Instance.IsStarted)
                            {
                                break;
                            }

                            // Save to primary backup file
                            BackupEngine.Instance.Grf.QuickMerge(grf);
                            BackupEngine.Instance.Grf.Reload();
                        }

                        GrfPath.Delete(grfPath);

                        // Deletes unused files, it's not necessary but it can pile up quickly
                        foreach (var file in _pendingBackups[key].Keys)
                        {
                            GrfPath.Delete(file);
                        }

                        _backupId = key;
                    }

                    // Remove old backups
                    if (!BackupEngine.Instance.IsStarted)
                    {
                        List <string> paths = BackupEngine.Instance.GetBackupFiles().OrderBy(long.Parse).ToList();

                        // Only delete if it's worth it.
                        if (paths.Count > BackupEngine.MaximumNumberOfBackups + 15)
                        {
                            while (paths.Count > BackupEngine.MaximumNumberOfBackups)
                            {
                                BackupEngine.Instance.Grf.Commands.RemoveFolder(paths[0]);
                                paths.RemoveAt(0);
                            }

                            BackupEngine.Instance.Grf.QuickSave();
                        }

                        // The GRF must always be closed
                        BackupEngine.Instance.Grf.Close();
                    }
                }
            }
            catch (Exception err) {
                IsCrashed = true;
                ErrorHandler.HandleException(err);
                ErrorHandler.HandleException("The backup engine has failed to save your files. It will be disabled until you reload the application.", ErrorLevel.NotSpecified);
            }
        }
Example #25
0
        public static void Loader(AbstractDb <int> db, string file)
        {
            if (file == null)
            {
                Debug.Ignore(() => DbDebugHelper.OnUpdate(db.DbSource, null, "achievement_list table will not be loaded."));
                return;
            }

            LuaList list;

            var table   = db.Table;
            var metaGrf = db.ProjectDatabase.MetaGrf;

            string outputPath = GrfPath.Combine(SdeAppConfiguration.TempPath, Path.GetFileName(file));

            byte[] itemData = metaGrf.GetData(file);

            if (itemData == null)
            {
                Debug.Ignore(() => DbDebugHelper.OnUpdate(db.DbSource, file, "File not found."));
                return;
            }

            File.WriteAllBytes(outputPath, itemData);

            if (!File.Exists(outputPath))
            {
                return;
            }

            if (Methods.ByteArrayCompare(itemData, 0, 4, new byte[] { 0x1b, 0x4c, 0x75, 0x61 }, 0))
            {
                // Decompile lub file
                Lub lub  = new Lub(itemData);
                var text = lub.Decompile();
                itemData = EncodingService.DisplayEncoding.GetBytes(text);
                File.WriteAllBytes(outputPath, itemData);
            }

            DbIOMethods.DetectAndSetEncoding(itemData);

            using (LuaReader reader = new LuaReader(outputPath, DbIOMethods.DetectedEncoding)) {
                list = reader.ReadAll();
            }

            LuaKeyValue itemVariable = list.Variables[0] as LuaKeyValue;

            if (itemVariable != null && itemVariable.Key == "achievement_tbl")
            {
                LuaList items = itemVariable.Value as LuaList;

                if (items != null)
                {
                    foreach (LuaKeyValue item in items.Variables)
                    {
                        _loadEntry(table, item);
                    }
                }
            }
            else
            {
                // Possible copy-paste data
                foreach (LuaKeyValue item in list.Variables)
                {
                    _loadEntry(table, item);
                }
            }

            Debug.Ignore(() => DbDebugHelper.OnLoaded(db.DbSource, metaGrf.FindTkPath(file), db));
        }
Example #26
0
        private void _listViewResults_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var item = _listViewResults.GetObjectAtPoint <ListViewItem>(e.GetPosition(_listViewResults));

            if (item != null)
            {
                HashSet <CmdInfo> commands = new HashSet <CmdInfo>();

                foreach (ValidationErrorView error in _listViewResults.SelectedItems)
                {
                    error.GetCommands(commands);
                }

                ContextMenu menu = new ContextMenu();

                foreach (var cmd in commands)
                {
                    var lcmd = cmd;

                    MenuItem mitem = new MenuItem {
                        Header = cmd.DisplayName, Icon = new Image {
                            Source = ApplicationManager.GetResourceImage(cmd.Icon)
                        }
                    };
                    mitem.Click += delegate {
                        var items = _listViewResults.SelectedItems.Cast <ValidationErrorView>().ToList();

                        _asyncOperation.SetAndRunOperation(new GrfThread(delegate {
                            List <object> dbs = new List <object>();

                            foreach (var serverDb in ServerDbs.ListDbs)
                            {
                                var db = _sdb.TryGetDb(serverDb);

                                if (db != null)
                                {
                                    if (db.AttributeList.PrimaryAttribute.DataType == typeof(int))
                                    {
                                        var adb = (AbstractDb <int>)db;
                                        dbs.Add(adb);
                                    }
                                    else if (db.AttributeList.PrimaryAttribute.DataType == typeof(string))
                                    {
                                        var adb = (AbstractDb <string>)db;
                                        dbs.Add(adb);
                                    }
                                }
                            }

                            foreach (var db in dbs)
                            {
                                _to <int>(db, _onBegin);
                                _to <string>(db, _onBegin);
                            }

                            try {
                                AProgress.Init(_validation);

                                _validation.Grf.Close();
                                _validation.Grf.Open(GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "missing_resources.grf"), GrfLoadOptions.OpenOrNew);

                                for (int i = 0; i < items.Count; i++)
                                {
                                    AProgress.IsCancelling(_validation);
                                    if (!lcmd.Execute(items[i], items))
                                    {
                                        return;
                                    }
                                    _validation.Progress = (float)i / items.Count * 100f;
                                }

                                if (_validation.Grf.IsModified)
                                {
                                    _validation.Progress = -1;
                                    _validation.Grf.QuickSave();
                                    _validation.Grf.Reload();
                                    _validation.Grf.Compact();
                                }
                            }
                            catch (OperationCanceledException) {
                            }
                            catch (Exception err) {
                                ErrorHandler.HandleException(err);
                            }
                            finally {
                                foreach (var db in dbs)
                                {
                                    _to <int>(db, _onEnd);
                                    _to <string>(db, _onEnd);
                                }

                                _validation.Grf.Close();
                                AProgress.Finalize(_validation);
                            }
                        }, _validation, 200, null, true, true));
                    };

                    menu.Items.Add(mitem);
                }

                item.ContextMenu        = menu;
                item.ContextMenu.IsOpen = true;
            }
            else
            {
                e.Handled = true;
            }
        }
        private void _textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try {
                if (!_tab.ItemsEventsDisabled)
                {
                    DisplayableProperty <TKey, TValue> .ApplyCommand(_tab, _attribute, _textBox.Text);
                }

                try {
                    byte[] data = _tab.ProjectDatabase.MetaGrf.GetDataBuffered(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath1, _textBox.Text.ExpandString()) + _ext));

                    if (data != null)
                    {
                        WpfUtilities.TextBoxOk(_textBox);
                        _wrapper1.Image = ImageProvider.GetImage(data, _ext);
                        _wrapper1.Image.MakePinkTransparent();
                        _imageResource.Tag    = _textBox.Text;
                        _imageResource.Source = _wrapper1.Image.Cast <BitmapSource>();
                    }
                    else
                    {
                        WpfUtilities.TextBoxError(_textBox);
                        _wrapper1.Image       = null;
                        _imageResource.Source = null;
                    }
                }
                catch (ArgumentException) {
                    WpfUtilities.TextBoxError(_textBox);
                    _wrapper1.Image       = null;
                    _imageResource.Source = null;
                }

                try {
                    byte[] data2 = _tab.ProjectDatabase.MetaGrf.GetDataBuffered(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath2, _textBox.Text.ExpandString()) + _ext));

                    if (data2 != null)
                    {
                        _wrapper2.Image = ImageProvider.GetImage(data2, _ext);
                        _wrapper2.Image.MakePinkTransparent();
                        _imagePreview.Tag    = _textBox.Text;
                        _imagePreview.Source = _wrapper2.Image.Cast <BitmapSource>();
                        //_imagePreview.Source.Freeze();
                    }
                    else
                    {
                        _wrapper2.Image      = null;
                        _imagePreview.Source = null;
                    }
                }
                catch (ArgumentException) {
                    _wrapper2.Image      = null;
                    _imagePreview.Source = null;
                }
            }
            catch (Exception err) {
                ErrorHandler.HandleException(err);
            }
        }
Example #28
0
        public bool Write(string dbPath, string subPath, ServerType serverType, FileType fileType = FileType.Detect)
        {
            SubPath = subPath;
            string filename = DbSource.Filename;

            DestinationServer = serverType;

            FileType = fileType;

            if ((fileType & FileType.Detect) == FileType.Detect)
            {
                if ((DbSource.SupportedFileType & FileType.Txt) == FileType.Txt)
                {
                    FileType = FileType.Txt;
                }

                if ((DbSource.SupportedFileType & FileType.Conf) == FileType.Conf)
                {
                    if (serverType == ServerType.Hercules)
                    {
                        FileType = FileType.Conf;
                        filename = DbSource.AlternativeName ?? filename;
                    }
                }

                if (FileType == FileType.Detect)
                {
                    FileType = FileType.Error;
                }
            }

            if (FileType == FileType.Error)
            {
                return(false);
            }

            if ((DbSource.SupportedFileType & FileType) != FileType)
            {
                return(false);
            }

            string ext = "." + FileType.ToString().ToLower();

            IsRenewal = false;

            if ((FileType & FileType.Sql) == FileType.Sql)
            {
                if (subPath == "re")
                {
                    FilePath = GrfPath.Combine(dbPath, filename + "_re" + ext);
                }
                else
                {
                    FilePath = GrfPath.Combine(dbPath, filename + ext);
                }
            }
            else
            {
                if (DbSource.UseSubPath)
                {
                    if (subPath == "re")
                    {
                        IsRenewal = true;
                    }

                    FilePath = GrfPath.Combine(dbPath, subPath, filename + ext);
                }
                else
                {
                    FilePath = GrfPath.Combine(dbPath, filename + ext);
                }
            }

            TextFileHelper.LatestFile = FilePath;

            string logicalPath = AllLoaders.DetectPath(DbSource);

            OldPath = AllLoaders.GetStoredFile(logicalPath);

            if (OldPath == null || !File.Exists(OldPath))
            {
                return(false);
            }

            if (_db.Attached["IsEnabled"] != null && !(bool)_db.Attached["IsEnabled"])
            {
                return(false);
            }

            GrfPath.CreateDirectoryFromFile(FilePath);

            if (!_db.Table.Commands.IsModified && logicalPath.IsExtension(FilePath.GetExtension()))
            {
                BackupEngine.Instance.Backup(logicalPath);
                _db.DbDirectCopy(this, _db);
                return(false);
            }

            BackupEngine.Instance.Backup(logicalPath);
            return(true);
        }
Example #29
0
 private string _convertLocalPath(string path)
 {
     return(GrfPath.Combine(DestPath, _convertPath(path).Replace("/", "\\")));
 }
        private void _textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try {
                byte[] data = _tab.Database.MetaGrf.GetData(EncodingService.FromAnyToDisplayEncoding(GrfPath.Combine(_grfPath, _textBox.Text) + _ext));

                if (data != null)
                {
                    if (_ext == ".spr")
                    {
                        try {
                            Spr spr = new Spr(data, false);

                            if (spr.Images.Count > 0)
                            {
                                _wrapper.Image = spr.Images[0];
                                _wrapper.Image.MakePinkTransparent();
                                _wrapper.Image.MakeFirstPixelTransparent();
                                _image.Tag    = _textBox.Text;
                                _image.Source = _wrapper.Image.Cast <BitmapSource>();
                            }
                            else
                            {
                                _cancelImage();
                            }
                        }
                        catch {
                            _cancelImage();
                        }
                    }
                    else
                    {
                        _wrapper.Image = ImageProvider.GetImage(data, _ext);
                        _wrapper.Image.MakePinkTransparent();
                        _wrapper.Image.MakeFirstPixelTransparent();
                        _image.Tag    = _textBox.Text;
                        _image.Source = _wrapper.Image.Cast <BitmapSource>();
                    }
                }
                else
                {
                    _cancelImage();
                }
            }
            catch (Exception err) {
                _cancelImage();
                ErrorHandler.HandleException(err);
            }
        }