Ejemplo n.º 1
0
        //Buttons
        private void buttonAccept_Click(object sender, EventArgs e)
        {
            ReturnNewName = textBoxNewName.Text;

            switch (FormMode)
            {
            case "rename":
            {
                string NewProfileName = NewProfileName = textBoxNewName.Text.Trim(new char[] { ' ' }), NewFolderName = "", NewFolderPath = "";
                byte   progress = 0;

                //Get existing folders
                string[] existingDirs = Directory.GetDirectories(InitialPath.Remove(InitialPath.LastIndexOf('\\') + 1));

                List <string> existingDirList = new List <string>();

                foreach (string dir in existingDirs)
                {
                    //Get name
                    existingDirList.Add(Utilities.TextUtilities.FromHexToString(Path.GetFileName(dir)));
                }

                if (NewProfileName != InitialName || existingDirList.Contains(NewProfileName))
                {
                    try
                    {
                        //New folder name
                        NewFolderName = Utilities.TextUtilities.FromStringToHex(NewProfileName);
                        NewFolderPath = InitialPath.Remove(InitialPath.LastIndexOf('\\') + 1) + NewFolderName;

                        progress = 1;

                        //Create folder and copy
                        Directory.CreateDirectory(NewFolderPath);
                        progress = 2;
                        Utilities.IO_Utilities.DirectoryCopy(InitialPath, NewFolderPath, true);
                        progress = 3;

                        //Decode profile.sii
                        FormMain tF          = new FormMain();
                        string[] profileFile = tF.NewDecodeFile(NewFolderPath + "\\profile.sii");
                        progress = 4;

                        SaveFileProfileData ProfileData = new SaveFileProfileData();
                        ProfileData.Prepare(profileFile);
                        progress = 5;

                        //New name
                        ProfileData.ProfileName = textBoxNewName.Text;
                        progress = 6;

                        //Write file
                        using (StreamWriter SW = new StreamWriter(NewFolderPath + "\\profile.sii", false))
                        {
                            ProfileData.WriteToStream(SW);
                        }
                        progress = 7;

                        //Make backup
                        if (checkBoxCreateBackup.Checked)
                        {
                            ZipFile.CreateFromDirectory(InitialPath, InitialPath + ".zip");
                        }
                        progress = 8;

                        //Delete old folder
                        Directory.Delete(InitialPath, true);
                        progress = 9;

                        ReturnNewName           = NewProfileName;
                        ReturnRenamedSuccessful = true;
                    }
                    catch
                    {
                        switch (progress)
                        {
                        case 0:
                            MessageBox.Show("Create new folder name failed");
                            break;

                        case 1:
                            MessageBox.Show("Directory was not created");
                            break;

                        case 2:
                            MessageBox.Show("Directory copy failed");
                            goto delete;

                        case 3:
                            MessageBox.Show("Profile not decoded");
                            goto delete;

                        case 4:
                            MessageBox.Show("Profile hase wrong version/format");
                            goto delete;

                        case 5:
                            MessageBox.Show("Profile name is not applied");
                            goto delete;

                        case 6:
                            MessageBox.Show("Profile write failed");
                            goto delete;

                        case 7:
                            MessageBox.Show("Profile backup creation failed. Keeping both versions. Delete old profile manually.");
                            break;

                        case 8:
                            MessageBox.Show("Deleting old profile failed. Keeping both versions. Delete old profile manually.");
                            ZipFile.ExtractToDirectory(InitialPath + ".zip", InitialPath);
                            File.Delete(InitialPath + ".zip");
                            break;
delete:
                            Directory.Delete(NewFolderPath);
                            break;

                        default:
                            MessageBox.Show("Unexpected error. Deleting new Profile.");
                            Directory.Delete(NewFolderPath);
                            break;
                        }
                    }
                }

                break;
            }

            case "clone":
            {
                //Get existing folders
                string[] existingDirs = Directory.GetDirectories(InitialPath.Remove(InitialPath.LastIndexOf('\\') + 1));

                List <string> existingDirList = new List <string>();

                foreach (string dir in existingDirs)
                {
                    //Get name
                    existingDirList.Add(Utilities.TextUtilities.FromHexToString(Path.GetFileName(dir)));
                }

                foreach (string newfile in textBoxNewName.Lines)
                {
                    string NewProfileName = "", NewFolderPath = "";
                    byte   progress = 0;

                    try
                    {
                        //Check empty lines
                        if (newfile.Length == 0 || newfile.Trim(new char[] { ' ' }).Length == 0)
                        {
                            continue;
                        }

                        NewProfileName = newfile.Trim(new char[] { ' ' });
                        //Check existing folders
                        if (NewProfileName == InitialName || existingDirList.Contains(NewProfileName))
                        {
                            continue;
                        }

                        //New folder
                        string NewProfileNameHex = Utilities.TextUtilities.FromStringToHex(NewProfileName);
                        NewFolderPath = InitialPath.Remove(InitialPath.LastIndexOf('\\') + 1) + NewProfileNameHex;

                        progress = 1;

                        //Validate If exist skip
                        if (Directory.Exists(NewFolderPath))
                        {
                            continue;
                        }

                        Directory.CreateDirectory(NewFolderPath);

                        progress = 2;

                        //Copy profile files .cfg .sii .png
                        //Get the files in the initial directory and copy them to the new location.
                        var files = Directory.EnumerateFiles(InitialPath, "*.*", SearchOption.TopDirectoryOnly).Where(s => s.EndsWith(".cfg") || s.EndsWith(".sii") || s.EndsWith(".png")).ToArray();

                        //Iterate files
                        foreach (string file in files)
                        {
                            string temppath = Path.Combine(NewFolderPath, Path.GetFileName(file)); //new file path with name

                            FileInfo tFI = new FileInfo(file);                                     //fileinfo
                            tFI.CopyTo(temppath, false);                                           //Copy
                        }

                        progress = 3;

                        //Create save folder
                        string NewSaveFolder = NewFolderPath + "\\save";
                        Directory.CreateDirectory(NewSaveFolder);

                        progress = 4;

                        //Copy saves
                        if (checkBoxFullCloning.Checked)
                        {
                            Utilities.IO_Utilities.DirectoryCopy(InitialPath + "\\save", NewSaveFolder, true);
                        }
                        else
                        {
                            Utilities.IO_Utilities.DirectoryCopy(InitialPath + "\\save\\autosave", NewSaveFolder + "\\autosave", false);
                        }

                        progress = 5;

                        //Decode profile.sii
                        string[] profileFile = ParentForm.NewDecodeFile(NewFolderPath + "\\profile.sii");
                        progress = 6;

                        SaveFileProfileData ProfileData = new SaveFileProfileData();
                        ProfileData.Prepare(profileFile);
                        progress = 7;

                        //New name
                        ProfileData.ProfileName  = NewProfileName;
                        ProfileData.CreationTime = Utilities.DateTimeUtilities.DateTimeToUnixTimeStamp();
                        progress = 8;

                        //Write file
                        using (StreamWriter SW = new StreamWriter(NewFolderPath + "\\profile.sii", false))
                        {
                            ProfileData.WriteToStream(SW);
                        }
                        progress = 9;

                        //Cloned folders
                        existingDirList.Add(NewProfileName);
                        ReturnClonedNames.Add(NewProfileName);
                    }
                    catch {
                        switch (progress)
                        {
                        case 0:
                            MessageBox.Show("Create new folder name failed");
                            break;

                        case 1:
                            MessageBox.Show("Directory was not created");
                            break;

                        case 2:
                            MessageBox.Show("Directory copy failed");
                            goto delete;

                        case 3:
                            MessageBox.Show("Directory for saves was not created");
                            goto delete;

                        case 4:
                            MessageBox.Show("Directory with saves copy failed");
                            goto delete;

                        case 5:
                            MessageBox.Show("Profile not decoded");
                            goto delete;

                        case 6:
                            MessageBox.Show("Profile hase wrong version/format");
                            goto delete;

                        case 7:
                            MessageBox.Show("Profile properties was not applied");
                            goto delete;

                        case 8:
                            MessageBox.Show("Profile write failed");
                            goto delete;
delete:
                            Directory.Delete(NewFolderPath);
                            break;

                        default:
                            MessageBox.Show("Unexpected error. Deleting new Profile.");
                            Directory.Delete(NewFolderPath);
                            break;
                        }
                    }
                }

                if (ReturnClonedNames.Count > 0)
                {
                    ReturnCloningSuccessful = true;
                }

                break;
            }
            }

            DialogResult = DialogResult.OK;
            Close();
        }
Ejemplo n.º 2
0
        //Buttons
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectionMode == SelectionMode.None || listBox1.SelectedIndex == -1)
            {
                listBox1.SelectionMode = SelectionMode.One;
                MessageBox.Show("Please select Base save file for New saves.");

                listBox1.SelectedValue = Globals.SelectedSavePath;
            }
            else
            {
                //Check if selected existing and valid save files 0,1 not 2,4
                DataRowView sI = (DataRowView)listBox1.SelectedItem;

                BaseSave = (string)sI.Row["savePath"];

                if ((byte)sI.Row[2] == 0 || (byte)sI.Row[2] == 1)
                {
                    string   SiiSavePath          = (string)sI.Row[0] + "\\game.sii"; //bool FileDecoded = false;
                    string[] tempSavefileInMemory = null;

                    //Load Base save file
                    if (!File.Exists(SiiSavePath))
                    {
                        MessageBox.Show("File does not exist in " + SiiSavePath);
                        MainForm.ShowStatusMessages("e", "error_could_not_find_file", this, statusStripCCpositions.Name, statusStripCCpositions.Items[0].Name);
                    }
                    else
                    {
                        MainForm.FileDecoded = false;
                        try
                        {
                            int decodeAttempt = 0;
                            while (decodeAttempt < 5)
                            {
                                tempSavefileInMemory = MainForm.NewDecodeFile(SiiSavePath, this, statusStripCCpositions.Name, statusStripCCpositions.Items[0].Name);

                                if (MainForm.FileDecoded)
                                {
                                    break;
                                }
                                decodeAttempt++;
                            }

                            if (decodeAttempt == 5)
                            {
                                MessageBox.Show("Could not decrypt after 5 attempts");
                                MainForm.ShowStatusMessages("e", "error_could_not_decode_file", this, statusStripCCpositions.Name, statusStripCCpositions.Items[0].Name);
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Could not read: " + SiiSavePath);
                        }

                        if ((tempSavefileInMemory == null) || (tempSavefileInMemory[0] != "SiiNunit"))
                        {
                            MessageBox.Show("Wrongly decoded Save file or wrong file format");
                            MainForm.ShowStatusMessages("e", "error_file_not_decoded", this, statusStripCCpositions.Name, statusStripCCpositions.Items[0].Name);
                        }
                        else
                        {
                            //Delete overwritten savefiles
                            foreach (KeyValuePair <string, string> ftd in FoldersToClear)
                            {
                                Directory.Delete(ftd.Key, true);
                            }

                            Globals.SavesHex = Directory.GetDirectories(Globals.SelectedProfilePath + @"\save").OrderByDescending(f => new FileInfo(f).LastWriteTime).ToArray();

                            List <byte> CustomFolders = new List <byte>();

                            //Find all custom folders
                            foreach (string saveF in Globals.SavesHex)
                            {
                                string saveFname = Path.GetFileName(saveF);
                                bool   result    = byte.TryParse(saveFname, out byte number);
                                if (result)
                                {
                                    CustomFolders.Add(number);
                                }
                            }

                            List <byte> NewCustomFolders = new List <byte>();

                            byte CustomFoldersCount = 1;
                            while (true)
                            {
                                if (CustomFolders.Exists(x => x == CustomFoldersCount))
                                {
                                }
                                else
                                {
                                    NewCustomFolders.Add(CustomFoldersCount);
                                }

                                if (NewCustomFolders.Count() == NewSave.Count)
                                {
                                    break;
                                }

                                CustomFoldersCount++;
                            }

                            //Create new numbered folder and new save files
                            int iSave = 0;
                            foreach (KeyValuePair <int, string[]> entry in NewSave)
                            {
                                //Create folder
                                string fp = Directory.GetParent(Globals.SavesHex[0]).FullName + "\\" + NewCustomFolders[iSave].ToString();
                                Directory.CreateDirectory(fp);

                                //Copy info file
                                string[] infoSii = MainForm.NewDecodeFile(BaseSave + @"\info.sii", this, statusStripCCpositions.Name, statusStripCCpositions.Items[0].Name);

                                //Prepare data
                                double tDT = MainForm.DateTimeToUnixTimeStamp(DateTime.UtcNow.ToLocalTime());

                                SavefileInfoData infoData = new SavefileInfoData();
                                infoData.SaveName = entry.Value[0];//Save name
                                infoData.FileTime = Convert.ToInt32(Math.Floor(tDT));

                                //Write info file
                                MainForm.WriteInfoFile(infoSii, fp + "\\info.sii", infoData);

                                //Create thumbnail files
                                //mat
                                Encoding utf8WithoutBom = new UTF8Encoding(false);
                                using (StreamWriter writer = new StreamWriter(fp + "\\preview.mat", true, utf8WithoutBom))
                                {
                                    writer.WriteLine(preview_mat);
                                }

                                //tobj
                                using (BinaryWriter binWriter = new BinaryWriter(File.Open(fp + "\\preview.tobj", FileMode.Create)))
                                {
                                    binWriter.Write(preview_tobj);
                                    string pathToTGA      = "/home/profiles/" + Globals.SelectedProfile + "/save/" + NewCustomFolders[iSave] + "/preview.tga";
                                    byte   filePathLength = (byte)pathToTGA.Length;
                                    binWriter.Write(filePathLength);
                                    binWriter.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
                                    binWriter.Write(Encoding.UTF8.GetBytes(pathToTGA));
                                }

                                //image tga
                                //Default thumbnail
                                TGA tgaImg; Bitmap newbmp = null; int custThumbCount = 0;

                                if (!checkBoxCustomThumbnail.Checked)
                                {
                                    string[] imgpaths = new string[] { "img\\" + MainForm.GameType + "\\autosave.dds" };
                                    newbmp = new Bitmap(MainForm.ExtImgLoader(imgpaths, 256, 128, 0, 0)[0]);
                                }
                                else if (checkBoxCustomThumbnail.Checked && Thumbnails.Length != 0)
                                {
                                    if (custThumbCount < Thumbnails.Length)
                                    {
                                        newbmp = new Bitmap(Thumbnails[custThumbCount]);
                                        custThumbCount++;
                                    }
                                    else
                                    {
                                        custThumbCount = 0;
                                        newbmp         = new Bitmap(Thumbnails[custThumbCount]);
                                    }
                                }

                                tgaImg = (TGA)newbmp;
                                tgaImg.Save(fp + "\\preview.tga");

                                //Create game save file
                                using (StreamWriter writer = new StreamWriter(fp + "\\game.sii", true))
                                {
                                    writer.Write(tempSavefileInMemory[0]);

                                    for (int line = 1; line < tempSavefileInMemory.Length; line++)
                                    {
                                        string SaveInMemLine = tempSavefileInMemory[line];

                                        if (SaveInMemLine.StartsWith(" truck_placement:"))
                                        {
                                            writer.Write("\r\n" + " truck_placement: " + entry.Value[1]);
                                            line++;
                                            writer.Write("\r\n" + " trailer_placement: (0, 0, 0) (1; 0, 0, 0)");
                                            line++;
                                            int slave_trailers = int.Parse(tempSavefileInMemory[line].Split(new char[] { ' ' })[2]);
                                            writer.Write("\r\n" + tempSavefileInMemory[line]);
                                            if (slave_trailers > 0)
                                            {
                                                for (int i = 0; i < slave_trailers; i++)
                                                {
                                                    writer.Write("\r\n" + " slave_trailer_placements[" + i + "]: (0, 0, 0) (1; 0, 0, 0)");
                                                    line++;
                                                }
                                            }
                                            continue;
                                        }

                                        //EndWrite:
                                        writer.Write("\r\n" + SaveInMemLine);
                                    }
                                }

                                iSave++;
                            }

                            //
                            buttonSave.Enabled = false;
                            GC.Collect();
                            MessageBox.Show("Saves are created.\nNow you can close this window.");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Not a valid save file for base file.\nPlease select existing save file not marked for deleting.");
                    //return;
                }
            }
        }