private void Start_Button_Click(object sender, RoutedEventArgs e)
        {
            string        dest          = "";
            Int32         bufferlength  = default_buffer;
            Int32         ttlvalue      = default_ttl;
            Int32         timeout       = default_timeout;
            Int32         interval      = default_interval;
            byte          checker       = 0x00; //A bitfield checker
            FieldUpdater  fieldUpdater  = FldUpd;
            StatusUpdater statusUpdater = StdUpd;

            Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Important, "Statring validation...");
            //Valid IP or domain name
            if (Destination_Fill.Text != "")
            {
                dest    = Destination_Fill.Text;
                checker = (byte)(checker | (byte)0x01);
            }
            else
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "No destination filled.");
            }
            //Valid buffer size
            if (Buffer_Size.Text != "")
            {
                if (CheckANumber(Buffer_Size.Text))
                {
                    if ((bufferlength = CheckNumberBetween(Convert.ToInt32(Buffer_Size.Text), 32, 65500)) != -1)
                    {
                        checker = (byte)(checker | (byte)0x02);
                    }
                    else
                    {
                        Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid buffer size setting.");
                    }
                }
                else
                {
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid buffer size Input.");
                }
            }
            else
            {
                Dispatcher.Invoke(fieldUpdater, ValueSign.FieldSign.BufferSize, bufferlength.ToString());
                checker = (byte)(checker | (byte)0x02);
            }
            //Valid TTL
            if (TTL_Count.Text != "")
            {
                if (CheckANumber(TTL_Count.Text))
                {
                    if ((ttlvalue = CheckNumberBetween(Convert.ToInt32(TTL_Count.Text), 1, 255)) != -1)
                    {
                        checker = (byte)(checker | (byte)0x04);
                    }
                    else
                    {
                        Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid TTL Value.");
                    }
                }
                else
                {
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid TTL Input.");
                }
            }
            else
            {
                Dispatcher.Invoke(fieldUpdater, ValueSign.FieldSign.TTL, ttlvalue.ToString());
                checker = (byte)(checker | (byte)0x04);
            }
            //Valid Timeout
            if (Timeout_Count.Text != "")
            {
                if (CheckANumber(Timeout_Count.Text))
                {
                    if ((timeout = CheckNumberLarger(Convert.ToInt32(Timeout_Count.Text), 1)) != -1)
                    {
                        checker = (byte)(checker | (byte)0x08);
                    }
                    else
                    {
                    }
                }
                else
                {
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid timeout input.");
                }
            }
            else
            {
                Dispatcher.Invoke(fieldUpdater, ValueSign.FieldSign.TimeOut, timeout.ToString());
                checker = (byte)(checker | (byte)0x08);
            }
            //Valid interval
            if (Interval_Count.Text != "")
            {
                if (CheckANumber(Interval_Count.Text))
                {
                    if ((interval = CheckNumberLarger(Convert.ToInt32(Interval_Count.Text), 1)) != -1)
                    {
                        checker = (byte)(checker | (byte)0x10);
                    }
                    else
                    {
                    }
                }
                else
                {
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Invalid interval input.");
                }
            }
            else
            {
                Dispatcher.Invoke(fieldUpdater, ValueSign.FieldSign.Interval, interval.ToString());
                checker = (byte)(checker | (byte)0x10);
            }
            //Check Valid
            if (checker == 0x1F)
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Information, "Validation completed, preparing...");
                DataSct.PingParam pingparamdata = new DataSct.PingParam
                {
                    destination = dest,
                    buffersize  = bufferlength,
                    dflag       = Is_DF.IsChecked.Value,
                    ttl         = ttlvalue,
                    timeout     = timeout,
                    interval    = interval
                };
                UIElementEnabler(false);
                pingworker = new Thread(new ParameterizedThreadStart(PingerLauncher))
                {
                    IsBackground = true,
                    Name         = "Ping Worker",
                    Priority     = ThreadPriority.AboveNormal
                };
                controlon.Reset();
                pingworker.Start((object)pingparamdata);
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Information, "Ping worker launcher has been called.");
            }
            else
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Information, "Validation failed for wrong parameters.");
            }
        }
Beispiel #2
0
        public void ProcessTag(ITag bitmapTag)
        {
            // I don't feel like writing structure definitions, poaching extraction code
            // #TODO: Wrap all of this up under a neat function for other uses
            bitmapTagData = null;
            processedPages.Clear();

            string groupName  = VariousFunctions.SterilizeTagGroupName(CharConstant.ToString(bitmapTag.Group.Magic)).Trim();
            string pluginPath = string.Format("{0}\\{1}\\{2}.xml", VariousFunctions.GetApplicationLocation() + @"Plugins", _buildInfo.Settings.GetSetting <string>("plugins"), groupName);

            if (!File.Exists(pluginPath) && _buildInfo.Settings.PathExists("fallbackPlugins"))
            {
                pluginPath = string.Format("{0}\\{1}\\{2}.xml", VariousFunctions.GetApplicationLocation() + @"Plugins", _buildInfo.Settings.GetSetting <string>("fallbackPlugins"), groupName);
            }

            if (pluginPath == null || !File.Exists(pluginPath))
            {
                StatusUpdater.Update("Plugin doesn't exist for 'bitmap', yet somehow you managed to get to the bitmap tab...");
                return;
            }

            using (IReader reader = _streamManager.OpenRead())
            {
                bitmapTagData = new DataBlockBuilder(reader, bitmapTag, _cache, _buildInfo);
                using (XmlReader pluginReader = XmlReader.Create(pluginPath))
                {
                    AssemblyPluginLoader.LoadPlugin(pluginReader, bitmapTagData);
                }
            }

            bool multiResouceMagic = false;             // debugging 8k textures spread across space and time

            // Resource check
            if (bitmapTagData.ReferencedResources.Count == 0)
            {
                StatusUpdater.Update("Unable to find any resources in the current tag to get bitmap data from!");
                return;
            }
            else
            {
                if (bitmapTagData.ReferencedResources.Count > 1)
                {
                    multiResouceMagic = true;
                }
                if (_cache.Resources != null)                 // mandrill compiled debugging cache
                {
                    using (IReader reader = _streamManager.OpenRead())
                    {
                        resourceTable = _cache.Resources.LoadResourceTable(reader);
                    }
                }
                else
                {
                    StatusUpdater.Update("Unable to find any resources in the cache file at all! Failed to display bitmap.");
                    return;
                }
            }

            // Grab all the raw pages required
            foreach (DatumIndex resourceDatum in bitmapTagData.ReferencedResources)
            {
                Resource currentResource = resourceTable.Resources[resourceDatum.Index];
                if (currentResource.Location == null)
                {
                    StatusUpdater.Update("A bitmap resource had a null location, bad doo doo! Fix yo compiler nerd.");
                    return;
                }

                foreach (ResourcePage currentPage in currentResource.Location.PagesToArray())
                {
                    if (currentPage == null)
                    {
                        continue;
                    }

                    using (FileStream fileStream = File.OpenRead(_cacheLocation))
                    {
                        ThirdGenCacheFile resourceFile   = (ThirdGenCacheFile)_cache;
                        Stream            resourceStream = fileStream;

                        if (currentPage.FilePath != null)                         // Mandrill compiles everything into a single cache
                        {
                            ResourceCacheInfo resourceCacheInfo = App.AssemblyStorage.AssemblySettings.HalomapResourceCachePaths.FirstOrDefault(r => r.EngineName == _buildInfo.Name);
                            string            resourceCachePath = (resourceCacheInfo != null && resourceCacheInfo.ResourceCachePath != "") ? resourceCacheInfo.ResourceCachePath : Path.GetDirectoryName(_cacheLocation);
                            resourceCachePath = Path.Combine(resourceCachePath ?? "", Path.GetFileName(currentPage.FilePath));

                            if (!File.Exists(resourceCachePath))
                            {
                                StatusUpdater.Update("Bitmap exists outside of the local cache, was unable to find this cache: " + Path.GetFileName(resourceCachePath));
                                return;
                            }

                            resourceStream = File.OpenRead(resourceCachePath);
                            resourceFile   = new ThirdGenCacheFile(new EndianReader(resourceStream, _cache.Endianness), _buildInfo, Path.GetFileName(_cacheLocation), _cache.BuildString);
                        }

                        byte[] pageData;
                        ResourcePageExtractor pageExtractor = new ResourcePageExtractor(resourceFile);
                        using (MemoryStream pageStream = new MemoryStream())
                        {
                            pageExtractor.ExtractPage(currentPage, resourceStream, pageStream);
                            pageData = new byte[pageStream.Length];
                            Buffer.BlockCopy(pageStream.GetBuffer(), 0, pageData, 0, (int)pageStream.Length);
                        }

                        processedPages.Add(pageData);                         // Store the page for use
                    }
                }
            }
        }
        public void Pinger(object pingparam)
        {
            DataSct.PingParam pingparamdata = (DataSct.PingParam)pingparam;
            Ping          pingwork          = new Ping();
            StatusUpdater statusUpdater     = StdUpd;

            try
            {
                PingReply pingReply = pingwork.Send(pingparamdata.destination, pingparamdata.timeout, new byte[pingparamdata.buffersize], new PingOptions(pingparamdata.ttl, pingparamdata.dflag));
                lock (totalaccesslock)
                {
                    if (sentpackcount < statisticpackcount)
                    {
                        sentpackcount += 1;
                    }
                }
                if (pingReply.Status == IPStatus.Success)
                {
                    PackCouter(true, pingReply.RoundtripTime);
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.CurrentPing, pingReply.RoundtripTime.ToString("0ms"));
                    if (((pingReply.RoundtripTime > pingparamdata.interval) && (pingparamdata.interval > 500)) || (pingReply.RoundtripTime >= 1000))
                    {
                        Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Warning, pingparamdata.destination + " ICMP reply latecy too long: " + pingReply.RoundtripTime.ToString("0ms"));
                    }
                }
                else
                {
                    PackCouter(false, null);
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, pingparamdata.destination + " " + ICMPErrorAnalasys(pingReply.Status));
                    Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.CurrentPing, "Failed");
                }
            }
            catch (Exception exception)
            {
                ExceptionLogcat(exception);
                controlon.Set();
            }
            double averagepingtime, packetlossrate;

            lock (statisticaccesslock)
            {
                averagepingtime = (double)totalrtt / (double)successpackcount;
                lock (totalaccesslock)
                {
                    packetlossrate = (double)failedpackcount / (double)sentpackcount;
                }
            }
            if (averagepingtime >= 0)
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.SmoothPing, averagepingtime.ToString("0.00ms"));
            }
            else
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.SmoothPing, "-");
            }
            if (packetlossrate >= 0)
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.PackageLoss, packetlossrate.ToString("0.00%"));
            }
            else
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.PackageLoss, "-");
            }
            if (!pingworker.IsAlive)
            {
                Dispatcher.Invoke(statusUpdater, ValueSign.StatusSign.Error, "Ping worker launcher died.");
            }
        }
Beispiel #4
0
        private async void CompileClick(object sender, RoutedEventArgs e)
        {
            // Logger Setup
            string folder = "Compiler";

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            string logPath = Path.Combine(folder, "ScriptCompiler.log");

            using (var logStream = File.Create(logPath))
            {
                // Create the logger and the exception collector. They are used for debugging.
                var traceListener      = new TextWriterTraceListener(logStream);
                var logger             = new ScriptCompilerLogger(traceListener);
                var exceptionCollector = new ParsingExceptionCollector();
                logger.Information($"Attempting to compile: {_scriptFile.Name}, Time: {DateTime.Now}");
                try
                {
                    // Get the script file.
                    string hsc = txtScript.Text;

                    // Measure the time it took to compile the scripts.
                    var stopWatch = Stopwatch.StartNew();

                    // Compile the scripts.
                    ScriptData compileData = await Task.Run(() => CompileScripts(hsc, _progress, logger, exceptionCollector));

                    stopWatch.Stop();
                    var    timeSpan           = stopWatch.Elapsed;
                    string compilationMessage = $"The scripts were successfully compiled in {Math.Round(timeSpan.TotalSeconds, 3)} seconds.";
                    logger.Information(compilationMessage);

                    // Show the message box.
                    var saveResult = MetroMessageBox.Show("Scripts Compiled", compilationMessage
                                                          + "\nWARNING: This compiler is not 100% accurate and could corrupt the map in rare cases. Making a backup before proceeding is advisable."
                                                          + "\n\nDo you want to save the changes to the file?", MetroMessageBox.MessageBoxButtons.YesNo);
                    if (saveResult == MetroMessageBox.MessageBoxResult.Yes)
                    {
                        //TODO: Move this to its own function.
                        await Task.Run(() =>
                        {
                            using (IStream stream = _streamManager.OpenReadWrite())
                            {
                                _scriptFile.SaveScripts(compileData, stream, _progress);
                                _cashefile.SaveChanges(stream);
                            }
                        });

                        RefreshMeta();
                        StatusUpdater.Update("Scripts saved");
                    }
                }
                // Handle Parsing Errors.
                catch (OperationCanceledException opEx)
                {
                    if (exceptionCollector.ContainsExceptions)
                    {
                        HandleParsingErrors(opEx, exceptionCollector, logger);
                    }
                    else
                    {
                        MetroMessageBox.Show("Operation Canceled", opEx.Message);
                    }
                }
                // Handle Compiler Errors.
                catch (CompilerException compEx)
                {
                    HandleCompilerErrors(compEx, logger);
                }
                finally
                {
                    logger.Flush();
                    ResetProgressBar();
                }
            }
        }
        private void UpdateMeta(MetaWriter.SaveType type, bool onlyUpdateChanged, bool showActionDialog = true)
        {
            if (type == MetaWriter.SaveType.File)
            {
                if (!ConfirmNewStringIds())
                {
                    return;
                }

                using (IStream stream = _fileManager.OpenReadWrite())
                {
#if DEBUG_SAVE_ALL
                    MetaWriter metaUpdate = new MetaWriter(writer, (uint)_tag.RawTag.MetaLocation.AsOffset(), _cache, _buildInfo, type, null, _stringIdTrie);
#else
                    var metaUpdate = new MetaWriter(stream, (uint)_tag.RawTag.MetaLocation.AsOffset(), _cache, _buildInfo, type,
                                                    _fileChanges, _stringIdTrie);
#endif
                    metaUpdate.WriteFields(_pluginVisitor.Values);
                    _cache.SaveChanges(stream);
                    _fileChanges.MarkAllUnchanged();
                }

                if (showActionDialog)
                {
                    MetroMessageBox.Show("Meta Saved", "The metadata has been saved back to the original file.");
                }
            }
            else if (_rteProvider != null)
            {
                var rteProvider = _rteProvider;
                if (App.AssemblyStorage.AssemblyNetworkPoke.NetworkRteProvider != null)
                {
                    rteProvider = App.AssemblyStorage.AssemblyNetworkPoke.NetworkRteProvider;
                }

                using (IStream metaStream = rteProvider.GetMetaStream(_cache))
                {
                    if (metaStream != null)
                    {
                        FieldChangeSet changes    = onlyUpdateChanged ? _memoryChanges : null;
                        var            metaUpdate = new MetaWriter(metaStream, _tag.RawTag.MetaLocation.AsPointer(), _cache, _buildInfo, type,
                                                                   changes, _stringIdTrie);
                        metaUpdate.WriteFields(_pluginVisitor.Values);

                        if (showActionDialog)
                        {
                            if (onlyUpdateChanged)
                            {
                                StatusUpdater.Update("All changed metadata has been poked to the game.");
                            }
                            else
                            {
                                StatusUpdater.Update("The metadata has been poked to the game.");
                            }
                        }
                    }
                    else
                    {
                        ShowConnectionError();
                    }
                }
            }
        }
        public void RefreshEditor(MetaReader.LoadType type)
        {
            string pluginpath = _pluginPath;

            if (!File.Exists(pluginpath))
            {
                pluginpath = _fallbackPluginPath;
            }

            if (pluginpath == null || !File.Exists(pluginpath))
            {
                UpdateMetaButtons(false);
                StatusUpdater.Update("Plugin doesn't exist. It can't be loaded for this tag.");
                return;
            }

            // Store the current search selection so it can be restored
            int searchSelectedItem = comboSearchResults.SelectedIndex;

            // Set the stream manager and base offset to use based upon the LoadType
            IStreamManager streamManager = null;
            long           baseOffset    = 0;

            switch (type)
            {
            case MetaReader.LoadType.File:
                streamManager = _fileManager;
                baseOffset    = (uint)_tag.RawTag.MetaLocation.AsOffset();
                break;

            case MetaReader.LoadType.Memory:
                if (_rteProvider == null)
                {
                    goto default;
                }

                if (_rteProvider.GetMetaStream(_cache) == null)
                {
                    ShowConnectionError();
                    return;
                }

                streamManager = new RTEStreamManager(_rteProvider, _cache);
                baseOffset    = _tag.RawTag.MetaLocation.AsPointer();
                break;

            default:
                MetroMessageBox.Show("Not Supported", "That feature is not supported for this game.");
                return;
            }

            // Load Plugin File
            using (XmlReader xml = XmlReader.Create(pluginpath))
            {
                _pluginVisitor = new ThirdGenPluginVisitor(_tags, _stringIdTrie, _cache.MetaArea,
                                                           App.AssemblyStorage.AssemblySettings.PluginsShowInvisibles);
                AssemblyPluginLoader.LoadPlugin(xml, _pluginVisitor);
            }

            _changeTracker = new FieldChangeTracker();
            _fileChanges   = new FieldChangeSet();
            _memoryChanges = new FieldChangeSet();

            var metaReader = new MetaReader(streamManager, baseOffset, _cache, _buildInfo, type, _fileChanges);

            _flattener = new ReflexiveFlattener(metaReader, _changeTracker, _fileChanges);
            _flattener.Flatten(_pluginVisitor.Values);
            metaReader.ReadFields(_pluginVisitor.Values);
            panelMetaComponents.ItemsSource = _pluginVisitor.Values;

            // Start monitoring fields for changes
            _changeTracker.RegisterChangeSet(_fileChanges);
            _changeTracker.RegisterChangeSet(_memoryChanges);
            _changeTracker.Attach(_pluginVisitor.Values);

            // Update Meta Toolbar
            UpdateMetaButtons(true);

            // Refresh search if needed
            if (searchSelectedItem != -1)
            {
                SearchTimer(null);
                if (searchSelectedItem <= (comboSearchResults.Items.Count - 1))
                {
                    comboSearchResults.SelectedIndex = searchSelectedItem;
                }
            }
        }
        public override void ExecuteTask(EnvironmentManager environmentManager, KillProcessTask updateTask,
                                         Logger logger, StatusUpdater statusUpdater)
        {
            Process[] processes;
            switch (updateTask.SearchMode)
            {
            case ProcessSearchMode.ProcessName:
                processes = Process.GetProcessesByName(updateTask.SearchString);
                break;

            case ProcessSearchMode.ProcessNameContains:
                processes = Process.GetProcesses().Where(x =>
                                                         x.ProcessName.IndexOf(updateTask.SearchString, StringComparison.OrdinalIgnoreCase) > -1)
                            .ToArray();
                break;

            case ProcessSearchMode.Filename:
                var filename = environmentManager.TranslateFilename(updateTask.SearchString);
                processes = Process.GetProcesses().Where(x =>
                {
                    try
                    {
                        return(string.Equals(x.MainModule.FileName, filename, StringComparison.OrdinalIgnoreCase));
                    }
                    catch (Exception)     //invalid access exception or something else
                    {
                        return(false);
                    }
                }).ToArray();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (processes.Length == 0)
            {
                logger.Info("No processes found, finish task");
                return;
            }

            logger.Info($"{processes.Length} process(es) found");
            foreach (var process in processes)
            {
                statusUpdater.UpdateStatus(statusUpdater.Translation.KillProcess, process.ProcessName);

                var    closedMainWindow = false;
                string processFilename  = null;

                logger.Debug($"Get process filename of process {process.ProcessName}");
                try
                {
                    processFilename = process.MainModule.FileName;
                }
                catch (Exception e)
                {
                    logger.Warning($"Getting process filename failed: {e.Message}");
                }

                logger.Debug("Attempt to close main window");
                try
                {
                    closedMainWindow = process.CloseMainWindow();
                }
                catch (Exception e)
                {
                    logger.Warning($"Closing main window failed: {e.Message}");
                }

                logger.Debug($"Closing main window result: {closedMainWindow}");
                try
                {
                    if (!closedMainWindow || !process.WaitForExit(3000))
                    {
                        logger.Info("Kill process");
                        process.Kill();
                    }
                }
                catch (Exception e)
                {
                    logger.Warning($"Killing process failed: {e.Message}");

                    if (updateTask.IsImportantForUpdateProcess)
                    {
                        throw;
                    }

                    continue;
                }

                if (processFilename != null)
                {
                    if (KilledProcesses == null)
                    {
                        KilledProcesses = new List <string>();
                    }
                    KilledProcesses.Add(processFilename);
                }
            }
        }