protected void OnBtnGenerateClicked(object sender, EventArgs e)
    {
        try {
            BarcodeLib.Barcode codeBar = new BarcodeLib.Barcode ();
            codeBar.Alignment = BarcodeLib.AlignmentPositions.CENTER;
            codeBar.IncludeLabel = true;
            codeBar.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;

            BarcodeLib.TYPE bCodeType = (BarcodeLib.TYPE)Enum.Parse (typeof(BarcodeLib.TYPE), cmbBarCodeType.ActiveText.ToString ());
            System.Drawing.Image imgTmpCodeBar = codeBar.Encode (bCodeType, txtData.Text.Trim (), System.Drawing.Color.Black, System.Drawing.Color.White, 300, 300);

            MemoryStream memoryStream = new MemoryStream();
            imgTmpCodeBar.Save(memoryStream, ImageFormat.Png);
            Gdk.Pixbuf pb = new Gdk.Pixbuf (memoryStream.ToArray());

            imgCodeBar.Pixbuf = pb;

        } catch (Exception err) {
            MessageDialog dlg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format ("Ocurrió un error \n {0}", err.Message));
            dlg.Run ();
            dlg.Destroy ();
            dlg.Dispose ();
            dlg = null;
        }
    }
Esempio n. 2
0
        public bool DisplayMessageDialog(string title, string message)
        {
            ManualResetEvent dialogCloseEvent = new ManualResetEvent(false);

            bool okPressed = false;

            Application.Invoke(delegate
            {
                MessageDialog msgDialog = null;

                try
                {
                    msgDialog = new MessageDialog(_parent, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
                    {
                        Title     = title,
                        Text      = message,
                        UseMarkup = true
                    };

                    msgDialog.SetDefaultSize(400, 0);

                    msgDialog.Response += (object o, ResponseArgs args) =>
                    {
                        if (args.ResponseId == ResponseType.Ok)
                        {
                            okPressed = true;
                        }

                        dialogCloseEvent.Set();
                        msgDialog?.Dispose();
                    };

                    msgDialog.Show();
                }
                catch (Exception ex)
                {
                    GtkDialog.CreateErrorDialog($"Error displaying Message Dialog: {ex}");

                    dialogCloseEvent.Set();
                }
            });

            dialogCloseEvent.WaitOne();

            return(okPressed);
        }
            private void OnGameMessage(object o, string user,
						    GameMessageType type)
            {
                string msg;
                switch (type)
                  {
                  case GameMessageType.Draw:
                      msg = "<big><b>{0} offers a draw</b>.\nDo you want to agree?</big>";
                      break;
                  case GameMessageType.Abort:
                      msg = "<big><b>{0} wants to abort the game</b>.\nDo you want to agree?</big>";
                      break;
                  default:
                      return;
                  }
                MessageDialog dlg = new MessageDialog (null,
                                       DialogFlags.
                                       Modal,
                                       MessageType.
                                       Question,
                                       ButtonsType.
                                       YesNo,
                                       true,
                                       msg,
                                       user);
                dlg.Modal = false;
                int ret = dlg.Run ();
                if (ret == (int) ResponseType.Yes)
                    client.CommandSender.
                        SendCommand ("accept " +
                                 user);
                else if (ret == (int) ResponseType.No)
                    client.CommandSender.
                        SendCommand ("decline " +
                                 user);
                dlg.Hide ();
                dlg.Dispose ();
            }
Esempio n. 4
0
        private void HandleInstallerDialog(FileChooserDialog fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";

                    if (firmwareVersion == null)
                    {
                        GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");

                        return;
                    }

                    SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "\n\nDo you want to continue?";

                    ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();

                    MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");

                    if (responseInstallDialog == ResponseType.Yes)
                    {
                        Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new Thread(() =>
                        {
                            Application.Invoke(delegate
                            {
                                waitingDialog.Run();
                            });

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    string message = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    GtkDialog.CreateInfoDialog(dialogTitle, message);
                                    Logger.Info?.Print(LogClass.Application, message);
                                });
                            }
                            catch (Exception ex)
                            {
                                Application.Invoke(delegate
                                {
                                    waitingDialog.Dispose();

                                    GtkDialog.CreateErrorDialog(ex.Message);
                                });
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        });

                        thread.Name = "GUI.FirmwareInstallerThread";
                        thread.Start();
                    }
                }
                catch (Exception ex)
                {
                    GtkDialog.CreateErrorDialog(ex.Message);
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }
Esempio n. 5
0
        internal void LoadApplication(string path)
        {
            if (_gameLoaded)
            {
                GtkDialog.CreateInfoDialog("Ryujinx", "A game has already been loaded", "Please close it first and try again.");
            }
            else
            {
                if (ConfigurationState.Instance.Logger.EnableDebug.Value)
                {
                    MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                    {
                        Title         = "Ryujinx - Warning",
                        Text          = "You have debug logging enabled, which is designed to be used by developers only.",
                        SecondaryText = "For optimal performance, it's recommended to disable debug logging. Would you like to disable debug logging now?"
                    };

                    if (debugWarningDialog.Run() == (int)ResponseType.Yes)
                    {
                        ConfigurationState.Instance.Logger.EnableDebug.Value = false;
                        SaveConfig();
                    }

                    debugWarningDialog.Dispose();
                }

                if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
                {
                    MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
                    {
                        Title         = "Ryujinx - Warning",
                        Text          = "You have shader dumping enabled, which is designed to be used by developers only.",
                        SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
                    };

                    if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
                    {
                        ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
                        SaveConfig();
                    }

                    shadersDumpWarningDialog.Dispose();
                }

                Logger.RestartTime();

                HLE.Switch device = InitializeSwitchInstance();

                UpdateGraphicsConfig();

                Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {_contentManager.GetCurrentFirmwareVersion()?.VersionString}");

                if (Directory.Exists(path))
                {
                    string[] romFsFiles = Directory.GetFiles(path, "*.istorage");

                    if (romFsFiles.Length == 0)
                    {
                        romFsFiles = Directory.GetFiles(path, "*.romfs");
                    }

                    if (romFsFiles.Length > 0)
                    {
                        Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
                        device.LoadCart(path, romFsFiles[0]);
                    }
                    else
                    {
                        Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
                        device.LoadCart(path);
                    }
                }
                else if (File.Exists(path))
                {
                    switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
                    {
                    case ".xci":
                        Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
                        device.LoadXci(path);
                        break;

                    case ".nca":
                        Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
                        device.LoadNca(path);
                        break;

                    case ".nsp":
                    case ".pfs0":
                        Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
                        device.LoadNsp(path);
                        break;

                    default:
                        Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
                        try
                        {
                            device.LoadProgram(path);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Logger.Error?.Print(LogClass.Application, "The file which you have specified is unsupported by Ryujinx.");
                        }
                        break;
                    }
                }
                else
                {
                    Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
                    device.Dispose();

                    return;
                }

                _emulationContext = device;

                _deviceExitStatus.Reset();

#if MACOS_BUILD
                CreateGameWindow(device);
#else
                Thread windowThread = new Thread(() =>
                {
                    CreateGameWindow(device);
                })
                {
                    Name = "GUI.WindowThread"
                };

                windowThread.Start();
#endif

                _gameLoaded = true;
                _stopEmulation.Sensitive = true;

                _firmwareInstallFile.Sensitive      = false;
                _firmwareInstallDirectory.Sensitive = false;

                DiscordIntegrationModule.SwitchToPlayingState(device.Application.TitleIdText, device.Application.TitleName);

                ApplicationLibrary.LoadAndSaveMetaData(device.Application.TitleIdText, appMetadata =>
                {
                    appMetadata.LastPlayed = DateTime.UtcNow.ToString();
                });
            }
        }
Esempio n. 6
0
        private void HandleInstallerDialog(FileChooserDialog fileChooser)
        {
            if (fileChooser.Run() == (int)ResponseType.Accept)
            {
                MessageDialog dialog = null;

                try
                {
                    string filename = fileChooser.Filename;

                    fileChooser.Dispose();

                    SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);

                    if (firmwareVersion == null)
                    {
                        dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                        dialog.Text = "Firmware not found.";

                        dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";

                        Logger.Error?.Print(LogClass.Application, $"A valid system firmware was not found in {filename}.");

                        dialog.Run();
                        dialog.Hide();
                        dialog.Dispose();

                        return;
                    }

                    SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();

                    string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";

                    if (currentVersion != null)
                    {
                        dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
                    }

                    dialogMessage += "Do you want to continue?";

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");

                    dialog.Text          = $"Install Firmware {firmwareVersion.VersionString}";
                    dialog.SecondaryText = dialogMessage;

                    int response = dialog.Run();

                    dialog.Dispose();

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");

                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                    dialog.SecondaryText = "Installing firmware...";

                    if (response == (int)ResponseType.Yes)
                    {
                        Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");

                        Thread thread = new Thread(() =>
                        {
                            GLib.Idle.Add(new GLib.IdleHandler(() =>
                            {
                                dialog.Run();
                                return(false);
                            }));

                            try
                            {
                                _contentManager.InstallFirmware(filename);

                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";

                                    dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";

                                    Logger.Info?.Print(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            catch (Exception ex)
                            {
                                GLib.Idle.Add(new GLib.IdleHandler(() =>
                                {
                                    dialog.Dispose();

                                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                                    dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";

                                    dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
                                                           " Please check logs for more info.";

                                    Logger.Error?.Print(LogClass.Application, ex.Message);

                                    dialog.Run();
                                    dialog.Dispose();

                                    return(false);
                                }));
                            }
                            finally
                            {
                                RefreshFirmwareLabel();
                            }
                        });

                        thread.Name = "GUI.FirmwareInstallerThread";
                        thread.Start();
                    }
                    else
                    {
                        dialog.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    if (dialog != null)
                    {
                        dialog.Dispose();
                    }

                    dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");

                    dialog.Text = "Parsing Firmware Failed.";

                    dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";

                    Logger.Error?.Print(LogClass.Application, ex.Message);

                    dialog.Run();
                    dialog.Dispose();
                }
            }
            else
            {
                fileChooser.Dispose();
            }
        }
Esempio n. 7
0
        private void ConfirmLoadAssembly(string [] selection)
        {
            Gtk.Entry     e_sPlugin          = null;
            string        l_sChoosenPlayer   = "";
            MessageDialog confirmationDialog = null;

            foreach (string s in selection)
            {
                confirmationDialog = new MessageDialog(this.Window,
                                                       DialogFlags.Modal |
                                                       DialogFlags.DestroyWithParent,
                                                       MessageType.Question,
                                                       ButtonsType.YesNo,
                                                       "What extension " + Path.GetFileName(s) + " should handle ?");
                VBox vbox = confirmationDialog.VBox;
                HBox hbox = new HBox(false, 4);
                vbox.PackStart(hbox, true, true, 0);

                e_sPlugin = new Gtk.Entry(".foobar");
                hbox.PackStart(e_sPlugin, false, false, 0);

                confirmationDialog.ShowAll();
                int res = confirmationDialog.Run();
                confirmationDialog.Hide();
                confirmationDialog.Dispose();

                if (res == (int)ResponseType.Yes)
                {
                    try
                    {
                        FileSelection fs = new FileSelection("Select your favorite player");
                        fs.HideFileopButtons();
                        CConfig config = CConfig.Instance;
                        fs.Complete((string)config["Interface/currentPath"]);
                        fs.Resizable = true;
                        fs.Modal     = true;
                        int r = fs.Run();
                        fs.Hide();
                        fs.Dispose();
                        if (r == (int)ResponseType.Ok)
                        {
                            l_sChoosenPlayer = fs.Selections[0];
                            plugins.LoadAssembly((string)((Gtk.Entry)e_sPlugin).Text, s);
                            try
                            {
                                CPluginManager.SetStatic(plugins.GetOwningType((string)((Gtk.Entry)e_sPlugin).Text), "Player", l_sChoosenPlayer);
                            }
                            catch (Exception e) { Console.WriteLine("Player not found"); }
                            PopulatePluginList();
                            ((Gtk.Button)m_xXML["applyButton"]).Sensitive = true;
                        }
                        else
                        {
                            throw new Exception("Loading aborted by user.");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Plugin error: " + e.Message);
                    }
                }
            }
        }
Esempio n. 8
0
            private static bool AskForConfirmation(Window win,
								string text)
            {
                MessageDialog md = new MessageDialog (win,
                                      DialogFlags.
                                      DestroyWithParent,
                                      MessageType.
                                      Question,
                                      ButtonsType.
                                      YesNo,
                                      String.
                                      Format
                                      ("<b>{0}</b>",
                                       text));

                int res = md.Run ();
                md.Hide ();
                md.Dispose ();
                return res == (int) ResponseType.Yes;
            }
            private void OnConnectionError(object o,
							string reason)
            {
                client.Stop ();
                // show error
                MessageDialog md = new MessageDialog (null,
                                      DialogFlags.
                                      DestroyWithParent,
                                      MessageType.
                                      Error,
                                      ButtonsType.
                                      Close,
                                      String.
                                      Format
                                      ("<b>{0}</b>",
                                       reason));

                md.Run ();
                md.Hide ();
                md.Dispose ();

                menubar.disconnectMenuItem.Sensitive = false;
                menubar.connectMenuItem.Sensitive = true;
                //configwidget.Sensitive = true;
                //Authenticate ();
            }
Esempio n. 10
0
        /// <summary>
        /// Parses a project file. The results are saved in FileManager.Wires, FileManager.Components, and FileManager.Labels.
        /// </summary>
        /// <param name="filename">The path of the project file.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidProjectDataException">The XML-file doesn't match with the schema.</exception>
        /// <exception cref="ArgumentException">Unable to access the file.</exception>
        public static void Load(string filename)
        {
            Vector2i getPos(XmlNode pos)
            {
                int x = int.Parse(pos.Attributes["x"].InnerText);
                int y = int.Parse(pos.Attributes["y"].InnerText);

                return(new Vector2i(x, y));
            }

            XmlDocument doc = new XmlDocument();
            XmlReader?  reader;

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType          = ValidationType.Schema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ProcessSchemaLocation;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            try
            {
                reader = XmlReader.Create(filename, settings);

                doc.Load(reader);

                /* STRUCTURE:
                 *  circuit
                 *    wires
                 *      wire
                 *        from < -x: int, y: int
                 *        to < -x: int, y: int
                 *      ...
                 *    components
                 *      component
                 *        type
                 *          "and" | "dFlipFlop" | "not"
                 *        location < -x: int, y: int
                 *        orientation
                 *          "north" | "east" | "south" | "west"...
                 *    labels
                 *      label < -size: int(10, 100)
                 *        location < -x: int, y: int
                 *        text
                 *          <string>...
                 */

                #region Parse Wires

                foreach (var _wire in doc.SelectNodes("/circuit/wires"))
                {
                    if (_wire != null)
                    {
                        XmlNode wire = ((XmlNode)_wire).FirstChild;

                        Vector2i start = getPos(wire.SelectSingleNode("from"));
                        Vector2i end   = getPos(wire.SelectSingleNode("to"));

                        if (start.X == end.X)
                        {
                            int length = Math.Abs(Math.Abs(end.Y) - start.Y);

                            Wires.Add(new Wire(start, length, Direction.Horizontal));
                        }
                        else if (start.Y == end.Y)
                        {
                            int length = Math.Abs(Math.Abs(end.X) - start.X);

                            Wires.Add(new Wire(start, length, Direction.Vertical));
                        }
                        else
                        {
                            throw new InvalidProjectDataException($"Start ({ start.X }, { start.Y }) and end ({ end.X }, { end.Y }) of wire #{ Wires.Count + 1 } has to be on the same axis.");
                        }

                        // FIXME: Diagonal wire support
                    }
                }

                #endregion

                #region Parse Components

                foreach (var _component in doc.SelectNodes("/circuit/components"))
                {
                    if (_component != null)
                    {
                        XmlNode component = ((XmlNode)_component).FirstChild;



                        ComponentType       type        = types[component.SelectSingleNode("type").InnerText];
                        Vector2i            location    = getPos(component.SelectSingleNode("location"));
                        Circuit.Orientation orientation = orientations[component.SelectSingleNode("orientation").InnerText];

                        Components.Add(InstanceData.Create(type, location, orientation));

                        // FIXME: Update list of gates.
                    }
                }

                #endregion

                #region Parse Labels

                foreach (var _label in doc.SelectNodes("/circuit/labels"))
                {
                    if (_label != null)
                    {
                        XmlNode label = ((XmlNode)_label).FirstChild;

                        int size = int.Parse(label.Attributes["size"].InnerText);

                        Vector2i location = getPos(label.SelectSingleNode("location"));

                        string text = label.SelectSingleNode("text").InnerText;

                        Labels.Add(new TextLabel(location, text, size));
                    }
                }

                #endregion

                #region Parse Recent Files

                foreach (var _recent_file in doc.SelectNodes("/circuit/recent_files"))
                {
                    if (_recent_file != null)
                    {
                        XmlNode file = ((XmlNode)_recent_file).FirstChild;

                        string text = file.SelectSingleNode("file_name").InnerText;

                        RecentFiles.Add(text);
                    }
                }

                #endregion

                // FIXME: Save wires, components, and labels in higher level objects

                IsNew = false;
                FileManager.filename = filename;
            }
            catch (Exception e)
            {
                if (e is XmlException || e is XPathException || e is InvalidProjectDataException || e is XmlSchemaException)
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Logik is unable to read file. Please choose a valid project file.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Not a project file.", e);
                }
                else
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Logik is unable to access choosen file.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Unable to access file.", e);
                }
            }

            if (reader != null)
            {
                reader.Close();
            }
        }
Esempio n. 11
0
        // <summary>
        // Writes the project to a specified file.
        // </summary>
        // <param name="filename">The path of the new project file.</param>
        public static void Save(string filename)
        {
            FileManager.filename = filename;
            if (FileManager.RecentFiles.Contains(filename))
            {
                IsNew = false;
                FileManager.RecentFiles.Remove(filename);
            }
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = true;

                XmlWriter xmlWriter = XmlWriter.Create(filename, settings);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("circuit");

                //wires
                xmlWriter.WriteStartElement("wires");
                foreach (var wire in Wires)
                {
                    xmlWriter.WriteStartElement("wire");

                    //from
                    xmlWriter.WriteStartElement("from");
                    xmlWriter.WriteAttributeString("x", wire.Pos.X.ToString());
                    xmlWriter.WriteAttributeString("y", wire.Pos.Y.ToString());
                    xmlWriter.WriteEndElement();

                    //to
                    xmlWriter.WriteStartElement("to");
                    xmlWriter.WriteAttributeString("x", wire.EndPos.X.ToString());
                    xmlWriter.WriteAttributeString("y", wire.EndPos.Y.ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();
                //end wires

                //components
                xmlWriter.WriteStartElement("components");

                foreach (var component in Components)
                {
                    xmlWriter.WriteStartElement("component");

                    xmlWriter.WriteStartElement("type");
                    xmlWriter.WriteString(component.Type.ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("location");
                    xmlWriter.WriteAttributeString("x", component.Position.X.ToString());
                    xmlWriter.WriteAttributeString("y", component.Position.X.ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("orientation");
                    xmlWriter.WriteString(component.Orientation.ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();

                //end components

                //labels
                xmlWriter.WriteStartElement("labels");

                foreach (var text_label in Labels)
                {
                    xmlWriter.WriteStartElement("label");
                    xmlWriter.WriteAttributeString("size", text_label.TextSize.ToString());

                    //text
                    xmlWriter.WriteStartElement("text");
                    xmlWriter.WriteString(text_label.Text);
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                }


                xmlWriter.WriteEndElement();
                //end labels

                //recent files

                xmlWriter.WriteStartElement("recent_files");

                foreach (var recent_file in RecentFiles)
                {
                    xmlWriter.WriteStartElement("file");

                    xmlWriter.WriteString(recent_file);

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();


                //end recent files


                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Close();
            }
            catch (Exception e)
            {
                //e is XmlException || e is XPathException || e is InvalidProjectDataException || e is XmlSchemaException
                if (e is XmlException || e is InvalidOperationException)
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Not Able To Save Data To File");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Failed to parse to XMl", e);
                }
                else
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Not Able To Save Data To File");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Failed to save to filename", e);
                }
            }
        }
Esempio n. 12
0
        public string GetPatchPoint()
        {
            string   newWeatherPath = null;
            string   dest           = PathUtilities.GetAbsolutePath(entryFilePath.Text, this.explorerPresenter.ApsimXFile.FileName);
            DateTime startDate      = calendarStart.Date;

            if (startDate.Year < 1889)
            {
                ShowMessage(MessageType.Warning, "SILO data is not available before 1889", "Invalid start date");
                return(null);
            }
            DateTime endDate = calendarEnd.Date;

            if (endDate.CompareTo(DateTime.Today) >= 0)
            {
                ShowMessage(MessageType.Warning, "SILO data end date can be no later than yesterday", "Invalid end date");
                return(null);
            }
            if (endDate.CompareTo(startDate) < 0)
            {
                ShowMessage(MessageType.Warning, "The end date must be after the start date!", "Invalid dates");
                return(null);
            }
            if (String.IsNullOrWhiteSpace(entryEmail.Text))
            {
                ShowMessage(MessageType.Warning, "The SILO data API requires you to provide your e-mail address", "E-mail address required");
                return(null);
            }

            // Patch point get a bit complicated. We need a BOM station number, but can't really expect the user
            // to know that in advance. So what we can attempt to do is use the provided lat and long in the geocoding service
            // to get us a placename, then use the SILO name search API to find a list of stations for us.
            // If we get multiple stations, we let the user choose the one they wish to use.

            string url = googleGeocodingApi + "latlng=" + entryLatitude.Text + ',' + entryLongitude.Text;

            try
            {
                MemoryStream stream = WebUtilities.ExtractDataFromURL(url);
                stream.Position = 0;
                JsonTextReader reader = new JsonTextReader(new StreamReader(stream));
                // Parsing the JSON gets a little tricky with a forward-reading parser. We're trying to track
                // down a "short_name" address component of "locality" type (I guess).
                string locName = "";
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.PropertyName && reader.Value.Equals("address_components"))
                    {
                        reader.Read();
                        if (reader.TokenType == JsonToken.StartArray)
                        {
                            JArray arr = JArray.Load(reader);
                            foreach (JToken token in arr)
                            {
                                JToken typesToken = token.Last;
                                JArray typesArray = typesToken.First as JArray;
                                for (int i = 0; i < typesArray.Count; i++)
                                {
                                    if (typesArray[i].ToString() == "locality")
                                    {
                                        locName = token["short_name"].ToString();
                                        break;
                                    }
                                }
                                if (!string.IsNullOrEmpty(locName))
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(locName))
                    {
                        break;
                    }
                }
                if (string.IsNullOrEmpty(locName))
                {
                    ShowMessage(MessageType.Error, "Unable to find a name key for the specified location", "Error determining location");
                    return(null);
                }
                int stationNumber = -1;
                if (locName.Contains(" ")) // the SILO API doesn't handle spaces well
                {
                    Regex regex = new Regex(" .");
                    locName = regex.Replace(locName, "_");
                }
                string       stationUrl    = String.Format("https://www.longpaddock.qld.gov.au/cgi-bin/silo/PatchedPointDataset.php?format=name&nameFrag={0}", locName);
                MemoryStream stationStream = WebUtilities.ExtractDataFromURL(stationUrl);
                stationStream.Position = 0;
                StreamReader streamReader = new StreamReader(stationStream);
                string       stationInfo  = streamReader.ReadToEnd();
                string[]     stationLines = stationInfo.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                if (stationLines.Length == 0)
                {
                    ShowMessage(MessageType.Error, "Unable to find a BOM station for this location", "Cannot find station");
                    return(null);
                }
                if (stationLines.Length == 1)
                {
                    string[] lineInfo = stationLines[0].Split('|');
                    stationNumber = Int32.Parse(lineInfo[0]);
                }
                else
                {
                    MessageDialog md = new MessageDialog(owningView.MainWidget.Toplevel as Window, DialogFlags.Modal, MessageType.Question, ButtonsType.OkCancel,
                                                         "Which station do you wish to use?");
                    md.Title = "Select BOM Station";
                    Gtk.TreeView tree = new Gtk.TreeView();
                    ListStore    list = new ListStore(typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string));
                    tree.AppendColumn("Number", new CellRendererText(), "text", 0);
                    tree.AppendColumn("Name", new CellRendererText(), "text", 1);
                    tree.AppendColumn("Latitude", new CellRendererText(), "text", 2);
                    tree.AppendColumn("Longitude", new CellRendererText(), "text", 3);
                    tree.AppendColumn("State", new CellRendererText(), "text", 4);
                    tree.AppendColumn("Elevation", new CellRendererText(), "text", 5);
                    tree.AppendColumn("Notes", new CellRendererText(), "text", 6);
                    foreach (string stationLine in stationLines)
                    {
                        string[] lineInfo = stationLine.Split('|');
                        list.AppendValues(lineInfo);
                    }
                    tree.Model         = list;
                    tree.RowActivated += OnPatchPointSoilSelected;

                    Box box = md.ContentArea;

                    box.PackStart(tree, true, true, 5);
                    box.ShowAll();

                    ResponseType result = (ResponseType)md.Run();
                    if (result == ResponseType.Ok)
                    {
                        TreeIter iter;
                        tree.Selection.GetSelected(out iter);
                        string stationString = (string)list.GetValue(iter, 0);
                        stationNumber = Int32.Parse(stationString);
                    }
                    md.Dispose();
                }
                if (stationNumber >= 0) // Phew! We finally have a station number. Now fetch the data.
                {
                    string pointUrl = String.Format("https://www.longpaddock.qld.gov.au/cgi-bin/silo/PatchedPointDataset.php?start={0:yyyyMMdd}&finish={1:yyyyMMdd}&station={2}&format=apsim&username={3}",
                                                    startDate, endDate, stationNumber, System.Net.WebUtility.UrlEncode(entryEmail.Text));
                    MemoryStream pointStream = WebUtilities.ExtractDataFromURL(pointUrl);
                    pointStream.Seek(0, SeekOrigin.Begin);
                    string headerLine = new StreamReader(pointStream).ReadLine();
                    pointStream.Seek(0, SeekOrigin.Begin);
                    if (headerLine.StartsWith("[weather.met.weather]"))
                    {
                        using (FileStream fs = new FileStream(dest, FileMode.Create))
                        {
                            pointStream.CopyTo(fs);
                            fs.Flush();
                        }
                        if (File.Exists(dest))
                        {
                            newWeatherPath = dest;
                        }
                    }
                    else
                    {
                        ShowMessage(MessageType.Error, new StreamReader(pointStream).ReadToEnd(), "Not valid APSIM weather data");
                    }
                }
            }
            catch (Exception err)
            {
                ShowMessage(MessageType.Error, err.Message, "Error");
            }
            return(newWeatherPath);
        }
Esempio n. 13
0
        /// <summary>
        /// Parses a project file. The results are saved in FileManager.Wires, FileManager.Components, and FileManager.Labels.
        /// </summary>
        /// <param name="filename">The path of the project file.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidProjectDataException">The XML-file doesn't match with the schema.</exception>
        /// <exception cref="ArgumentException">Unable to access the file.</exception>
        public static void Load(string filename)
        {
            Vector2i getPos(XmlNode pos)
            {
                int x = int.Parse(pos.Attributes["x"].InnerText);
                int y = int.Parse(pos.Attributes["y"].InnerText);

                return(new Vector2i(x, y));
            }

            //HACK: What does "Could not find schema information for the element '<element>'." for every element mean!?

            XmlSchemaSet schema = new XmlSchemaSet();
            // currentDirectory = ~\bin\Debug\netcoreapp3.1
            string path = Directory.GetCurrentDirectory() + "\\..\\..\\..\\File";

            schema.Add("http://www.w3.org/2001/XMLSchema", path + "\\structure.xsd");

            XmlDocument doc = new XmlDocument();

            doc.Schemas = schema;
            XmlReader?reader;

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType          = ValidationType.Schema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ProcessInlineSchema;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ProcessSchemaLocation;
            settings.ValidationFlags        |= XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            try
            {
                reader = XmlReader.Create(filename, settings);

                doc.Load(reader);

                #region Parse Wires

                foreach (var _wire in doc.SelectNodes("/circuit/wires"))
                {
                    if (_wire != null)
                    {
                        XmlNode wire = ((XmlNode)_wire).FirstChild;

                        Vector2i start = getPos(wire.SelectSingleNode("from"));
                        Vector2i end   = getPos(wire.SelectSingleNode("to"));

                        if (start.X == end.X)
                        {
                            int length = Math.Abs(Math.Abs(end.Y) - start.Y);

                            Wires.Add(new Wire(start, length, Direction.Horizontal));
                        }
                        else if (start.Y == end.Y)
                        {
                            int length = Math.Abs(Math.Abs(end.X) - start.X);

                            Wires.Add(new Wire(start, length, Direction.Vertical));
                        }
                        else
                        {
                            throw new InvalidProjectDataException($"Start ({ start.X }, { start.Y }) and end ({ end.X }, { end.Y }) of wire #{ Wires.Count + 1 } has to be on the same axis.");
                        }

                        // FIXME: Diagonal wire support
                    }
                }

                #endregion

                #region Parse Components

                foreach (var _component in doc.SelectNodes("/circuit/components"))
                {
                    if (_component != null)
                    {
                        XmlNode component = ((XmlNode)_component).FirstChild;

                        ComponentType       type        = types[component.SelectSingleNode("type").InnerText];
                        Vector2i            location    = getPos(component.SelectSingleNode("location"));
                        Circuit.Orientation orientation = orientations[component.SelectSingleNode("orientation").InnerText];

                        Components.Add(InstanceData.Create(type, location, orientation));

                        // FIXME: Update list of gates.
                    }
                }

                #endregion

                #region Parse Labels

                foreach (var _label in doc.SelectNodes("/circuit/labels"))
                {
                    if (_label != null)
                    {
                        XmlNode label = ((XmlNode)_label).FirstChild;

                        int      size     = int.Parse(label.Attributes["size"].InnerText);
                        Vector2i location = getPos(label.SelectSingleNode("location"));
                        string   text     = label.SelectSingleNode("text").InnerText;

                        Labels.Add(new TextLabel(location, text, size));
                    }
                }

                #endregion

                // FIXME: Save wires, components, and labels in higher level objects

                IsNew = false;
                FileManager.filename = filename;
            }
            catch (Exception e)
            {
                if (e is XmlException || e is XPathException || e is InvalidProjectDataException || e is XmlSchemaException || e is KeyNotFoundException)
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Logik is unable to read file. Please choose a valid project file.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Not a project file.", e);
                }
                else
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Logik is unable to access choosen file.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Unable to access file.", e);
                }
            }

            if (reader != null)
            {
                reader.Close();
            }
        }
Esempio n. 14
0
        // <summary>
        // Writes the project to a specified file.
        // </summary>
        // <param name="filename">The path of the new project file.</param>
        public static void Save(string filename)
        {
            IsNew = false;
            FileManager.filename = filename;

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = true;

                XmlWriter xmlWriter = XmlWriter.Create(filename, settings);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("circuit");

                #region Parse Wires

                xmlWriter.WriteStartElement("wires");
                foreach (var wire in Wires)
                {
                    xmlWriter.WriteStartElement("wire");

                    //from
                    xmlWriter.WriteStartElement("from");
                    xmlWriter.WriteAttributeString("x", wire.Pos.X.ToString());
                    xmlWriter.WriteAttributeString("y", wire.Pos.Y.ToString());
                    xmlWriter.WriteEndElement();

                    //to
                    xmlWriter.WriteStartElement("to");
                    xmlWriter.WriteAttributeString("x", wire.EndPos.X.ToString());
                    xmlWriter.WriteAttributeString("y", wire.EndPos.Y.ToString());
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();

                #endregion

                #region Parse Components

                xmlWriter.WriteStartElement("components");

                foreach (var component in Components)
                {
                    xmlWriter.WriteStartElement("component");

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();

                #endregion

                #region Parse Labels

                xmlWriter.WriteStartElement("labels");

                foreach (var text_label in Labels)
                {
                    xmlWriter.WriteStartElement("label");
                    xmlWriter.WriteAttributeString("size", text_label.TextSize.ToString());

                    //text
                    xmlWriter.WriteStartElement("text");
                    xmlWriter.WriteString(text_label.Text);
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteEndElement();
                }

                xmlWriter.WriteEndElement();

                #endregion

                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
                xmlWriter.Close();
            }
            catch (Exception e)
            {
                if (e is XmlException || e is InvalidOperationException)
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Unable to save project due to XML error.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException("Failed to parse to XML.", e);
                }
                else
                {
                    MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Unable to save project due to access/write error.");
                    md.Run();
                    md.Dispose();

                    throw new ArgumentException($"Failed to save to { filename }.", e);
                }
            }
        }
Esempio n. 15
0
        private void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Buffer.Text;

            if (String.IsNullOrEmpty(str))
            {
                var md = new MessageDialog(TooltipWindow,
                                           DialogFlags.DestroyWithParent, MessageType.Warning,
                                           ButtonsType.Close, "发送内容不能为空!");
                md.Run();
                md.Dispose();
                //MessageBox.Show("发送内容不能为空!", MediaTypeNames.Text);
                //txtSend.Focus();
                return;
            }

            // 多次发送
            var count = (Int32)numMutilSend.Value;
            var sleep = (Int32)numSleep.Value;
            var ths   = (Int32)numThreads.Value;

            if (count <= 0)
            {
                count = 1;
            }
            if (sleep <= 0)
            {
                sleep = 1;
            }

            SaveConfig();

            var cfg = NetConfig.Current;

            // 处理换行
            str = str.Replace("\n", "\r\n");
            var buf = cfg.HexSend ? str.ToHex() : str.GetBytes();
            var pk  = new Packet(buf);

            if (_Client != null)
            {
                if (ths <= 1)
                {
                    _Client.SendMulti(pk, count, sleep);
                }
                else
                {
                    var any  = _Client.Local.Address.IsAny();
                    var list = new List <ISocketClient>();
                    for (var i = 0; i < ths; i++)
                    {
                        var client = _Client.Remote.CreateRemote();
                        if (!any)
                        {
                            client.Local.EndPoint = new IPEndPoint(_Client.Local.Address, 2000 + i);
                        }
                        client.StatSend    = _Client.StatSend;
                        client.StatReceive = _Client.StatReceive;
                        //client.SendMulti(buf, count, sleep);

                        list.Add(client);
                    }
                    var ts = new List <Task>();
                    for (var i = 0; i < ths; i++)
                    {
                        var task = list[i].SendConcurrency(pk, count, sleep);
                        ts.Add(task);
                    }

                    _Send = TaskEx.WhenAll(ts);
                }
            }
#if !NET4
            else if (_Server != null)
            {
                TaskEx.Run(async() =>
                {
                    BizLog.Info("准备向[{0}]个客户端发送[{1}]次[{2}]的数据", _Server.SessionCount, count, buf.Length);
                    for (var i = 0; i < count && _Server != null; i++)
                    {
                        var sw = Stopwatch.StartNew();
                        var cs = await _Server.SendAllAsync(buf);
                        sw.Stop();
                        BizLog.Info("{3}/{4} 已向[{0}]个客户端发送[{1}]数据 {2:n0}ms", cs, buf.Length, sw.ElapsedMilliseconds, i + 1, count);
                        if (sleep > 0)
                        {
                            await TaskEx.Delay(sleep);
                        }
                    }
                });
            }
#endif
        }
Esempio n. 16
0
        private void RealEditValidator(object sender, EventArgs e)
        {
            try
            {
                Entry tb = sender as Entry;
                if (tb != null)
                {
                    FoodSupplement.SuppAttribute tagEnum;
                    if (entryLookup.TryGetValue(tb, out tagEnum))
                    {
                        double maxVal = 0.0;
                        double scale  = 1.0;
                        switch (tagEnum)
                        {
                        case FoodSupplement.SuppAttribute.spaDMP:
                        case FoodSupplement.SuppAttribute.spaDMD:
                        case FoodSupplement.SuppAttribute.spaEE:
                        case FoodSupplement.SuppAttribute.spaDG:
                            maxVal = 100.0;
                            scale  = 0.01;
                            break;

                        case FoodSupplement.SuppAttribute.spaMEDM:
                            maxVal = 20.0;
                            break;

                        case FoodSupplement.SuppAttribute.spaCP:
                            maxVal = 300.0;
                            scale  = 0.01;
                            break;

                        case FoodSupplement.SuppAttribute.spaPH:
                        case FoodSupplement.SuppAttribute.spaSU:
                        case FoodSupplement.SuppAttribute.spaADIP:
                            maxVal = 100.0;
                            scale  = 0.01;
                            break;

                        default:
                            maxVal = 100.0;
                            break;
                        }
                        double value;
                        bool   cancel = false;
                        if (string.IsNullOrWhiteSpace(tb.Text)) // Treat blank as a value of 0.
                        {
                            value = 0.0;
                        }
                        else if (!Double.TryParse(tb.Text, out value) || value < 0.0 || value > maxVal)
                        {
                            // e.Cancel = true;
                            cancel = true;
                            MessageDialog md = new MessageDialog(MainWidget.Toplevel as Window, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok,
                                                                 String.Format("Value should be a number in the range 0 to {0:F2}", maxVal));
                            md.Title = "Invalid entry";
                            md.Run();
                            md.Dispose();
                        }
                        if (!cancel)
                        {
                            if (SuppAttrChanged != null)
                            {
                                TSuppAttrArgs args = new TSuppAttrArgs();
                                args.Attr    = (int)tagEnum;
                                args.AttrVal = value * scale;
                                if (SuppAttrChanged != null)
                                {
                                    SuppAttrChanged.Invoke(sender, args);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                ShowError(err);
            }
        }
Esempio n. 17
0
        public void RunCommand(OCMMainWindow win)
        {
            string cmd = m_command;

            if (cmd.Contains("%gpxgc%"))
            {
                GPXWriter            writer   = new GPXWriter();
                String               tempPath = System.IO.Path.GetTempPath();
                String               tempFile = tempPath + "ocm_export.gpx";
                ExportProgressDialog dlg      = new ExportProgressDialog(writer);
                dlg.AutoClose       = true;
                dlg.Title           = Catalog.GetString("Preparing GPX File");
                dlg.WaypointsOnly   = false;
                dlg.CompleteCommand = m_command.Replace("%gpxgc%", tempFile);
                dlg.Start(tempFile, win.CacheList.UnfilteredCaches, GPSProfileList.GetDefaultMappings(), win.App.CacheStore);
            }
            else if (cmd.Contains("%gpx%"))
            {
                GPXWriter            writer   = new GPXWriter();
                String               tempPath = System.IO.Path.GetTempPath();
                String               tempFile = tempPath + "ocm_export.gpx";
                ExportProgressDialog dlg      = new ExportProgressDialog(writer);
                dlg.AutoClose       = true;
                dlg.Title           = Catalog.GetString("Preparing GPX File");
                dlg.WaypointsOnly   = true;
                dlg.CompleteCommand = m_command.Replace("%gpx%", tempFile);
                dlg.Start(tempFile, win.CacheList.UnfilteredCaches, GPSProfileList.GetDefaultMappings(), win.App.CacheStore);
            }
            else if (cmd.Contains("%selected%"))
            {
                if (win.CacheList.SelectedCache == null)
                {
                    MessageDialog edlg = new MessageDialog(null, DialogFlags.Modal,
                                                           MessageType.Error, ButtonsType.Ok,
                                                           Catalog.GetString("No cache selected."));
                    edlg.Run();
                    edlg.Hide();
                    edlg.Dispose();
                    return;
                }
                GPXWriter            writer   = new GPXWriter();
                String               tempPath = System.IO.Path.GetTempPath();
                String               tempFile = tempPath + "ocm_export.gpx";
                ExportProgressDialog dlg      = new ExportProgressDialog(writer);
                dlg.AutoClose       = true;
                dlg.Title           = Catalog.GetString("Preparing GPX File");
                dlg.WaypointsOnly   = true;
                dlg.CompleteCommand = m_command.Replace("%selected%", tempFile);
                List <Geocache> cache = new List <Geocache>();
                cache.Add(win.CacheList.SelectedCache);
                dlg.Start(tempFile, cache, GPSProfileList.GetDefaultMappings(), win.App.CacheStore);
            }
            else if (cmd.Contains("%names%") && win.CacheList.UnfilteredCaches.Count > 0)
            {
                String names = "";
                foreach (Geocache cache in win.CacheList.UnfilteredCaches)
                {
                    if (names.Length > 0)
                    {
                        names += ' ';
                    }
                    names += cache.Name;
                }
                Process.Start(Utilities.StringToStartInfo(cmd.Replace("%names%", names)));
            }
            else if (cmd.Contains("%selectedname%"))
            {
                if (win.CacheList.SelectedCache == null)
                {
                    MessageDialog edlg = new MessageDialog(null, DialogFlags.Modal,
                                                           MessageType.Error, ButtonsType.Ok,
                                                           Catalog.GetString("No cache selected."));
                    edlg.Run();
                    edlg.Hide();
                    edlg.Dispose();
                    return;
                }
                Process.Start(Utilities.StringToStartInfo(cmd.Replace("%selectedname%", win.CacheList.SelectedCache.Name)));
            }
            else if (cmd.Contains("%finds%"))
            {
                GPXWriter writer = new GPXWriter();
                writer.IsMyFinds    = true;
                writer.MyFindsOwner = win.App.OwnerIDs[0];
                String tempPath          = System.IO.Path.GetTempPath();
                String tempFile          = tempPath + "ocm_finds.gpx";
                ExportProgressDialog dlg = new ExportProgressDialog(writer);
                dlg.AutoClose       = true;
                dlg.Title           = Catalog.GetString("Preparing GPX File");
                dlg.WaypointsOnly   = true;
                dlg.CompleteCommand = m_command.Replace("%finds%", tempFile);
                //dlg.Start(tempFile, Engine.getInstance().Store.GetFinds(), GPSProfileList.GetDefaultMappings(), mon.CacheStore);
            }
            else
            {
                Process.Start(Utilities.StringToStartInfo(m_command));
            }
        }
            private void ShowChallengeDialog(MatchChallenge mc)
            {
                StringBuilder buf = new StringBuilder ();
                string rating;

                if (mc.OpponentsRating != 0)
                    rating = mc.OpponentsRating.
                        ToString ();
                else
                    rating = "----";
                buf.Append (String.
                        Format
                        ("<big><b>{0} ({1}) wants to play a {2} game</b></big>\n",
                         mc.Opponent, rating,
                         mc.Category));
                buf.Append (String.
                        Format
                        ("<b><u>Time:</u> {0} </b><i>mins</i>, <b><u>Increment:</u></b> {1}\n",
                         mc.Time, mc.Increment));
                if (mc.Color != null)
                    buf.Append (String.
                            Format
                            ("\n<b><u>Color:</u></b> {0}\n",
                             mc.Color));

                buf.Append
                    ("\n\n<b>Do you want to play?</b>");

                MessageDialog dlg = new MessageDialog (null,
                                       DialogFlags.
                                       Modal,
                                       MessageType.
                                       Question,
                                       ButtonsType.
                                       YesNo,
                                       true,
                                       buf.
                                       ToString
                                       ());
                dlg.Modal = false;
                dlg.GrabFocus ();
                int ret = dlg.Run ();
                if (ret == (int) ResponseType.Yes)
                    client.CommandSender.
                        SendCommand ("accept");
                else if (ret == (int) ResponseType.No)
                    client.CommandSender.
                        SendCommand ("decline");
                dlg.Hide ();
                dlg.Dispose ();
            }
Esempio n. 19
0
        private async void btnSend_Click(Object sender, EventArgs e)
        {
            var str = txtSend.Buffer.Text;

            if (String.IsNullOrEmpty(str))
            {
                var md = new MessageDialog(this.TooltipWindow,
                                           DialogFlags.DestroyWithParent, MessageType.Warning,
                                           ButtonsType.Close, "发送内容不能为空!");
                md.Run();
                md.Dispose();
                // MessageBox.Show("发送内容不能为空!", Text);
                // txtSend.Focus();
                return;
            }

            // 多次发送
            var count = (Int32)numMutilSend.Value;
            var sleep = (Int32)numSleep.Value;
            var ths   = (Int32)numThreads.Value;

            if (count <= 0)
            {
                count = 1;
            }
            if (sleep <= 0)
            {
                sleep = 1;
            }

            SaveConfig();

            var uri = new NetUri(cbAddr.ActiveText);
            var cfg = ApiConfig.Current;

            // 处理换行
            str = str.Replace("\n", "\r\n");

            var act    = cbAction.ActiveText;
            var action = act.Substring(" ", "(");

            if (action.IsNullOrEmpty())
            {
                return;
            }

            var rtype = act.Substring(null, " ").GetTypeEx();

            if (rtype == null)
            {
                rtype = typeof(Object);
            }
            var ps = act.Substring("(", ")").Split(",");

            // 构造消息,二进制优先
            Object args = null;

            if (ps.Length == 1 && ps[0].StartsWith("Packet "))
            {
                args = new Packet(str.GetBytes());
            }
            else
            {
                var dic = new JsonParser(str).Decode() as IDictionary <String, Object>;
                if (dic == null || dic.Count == 0)
                {
                    dic = null;
                }
                args = dic;
            }

            if (_Client == null)
            {
                return;
            }

            _Invoke    = 0;
            _Cost      = 0;
            _TotalCost = 0;

            //var ct = _Client.Client;
            var list = new List <ApiClient> {
                _Client
            };

            for (var i = 0; i < ths - 1; i++)
            {
                var client = new ApiClient(uri + "");
                //var ct2 = client.Client;
                //ct2.Log = ct.Log;
                //ct2.LogSend = ct.LogSend;
                //ct2.LogReceive = ct.LogReceive;
                //ct2.StatSend = ct.StatSend;
                //ct2.StatReceive = ct.StatReceive;

                client.StatSend    = _Client.StatSend;
                client.StatReceive = _Client.StatReceive;

                list.Add(client);
            }
            //Parallel.ForEach(list, k => OnSend(k, act, args, count));
            var sw = Stopwatch.StartNew();
            var ts = list.Select(k => OnSend(k, rtype, action, args, count, sleep)).ToList();

            await TaskEx.WhenAll(ts);

            sw.Stop();
            _TotalCost = sw.Elapsed.TotalMilliseconds;
        }
Esempio n. 20
0
        private void ExtractSection(NcaSectionType ncaSectionType)
        {
            FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to extract into", null, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Extract", ResponseType.Accept);

            fileChooser.SetPosition(WindowPosition.Center);

            int    response    = fileChooser.Run();
            string destination = fileChooser.Filename;

            fileChooser.Dispose();

            if (response == (int)ResponseType.Accept)
            {
                Thread extractorThread = new Thread(() =>
                {
                    string sourceFile = _gameTableStore.GetValue(_rowIter, 9).ToString();

                    Gtk.Application.Invoke(delegate
                    {
                        _dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Cancel, null)
                        {
                            Title          = "Ryujinx - NCA Section Extractor",
                            Icon           = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
                            SecondaryText  = $"Extracting {ncaSectionType} section from {System.IO.Path.GetFileName(sourceFile)}...",
                            WindowPosition = WindowPosition.Center
                        };

                        int dialogResponse = _dialog.Run();
                        if (dialogResponse == (int)ResponseType.Cancel || dialogResponse == (int)ResponseType.DeleteEvent)
                        {
                            _cancel = true;
                            _dialog.Dispose();
                        }
                    });

                    using (FileStream file = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                    {
                        Nca mainNca  = null;
                        Nca patchNca = null;

                        if ((System.IO.Path.GetExtension(sourceFile).ToLower() == ".nsp") ||
                            (System.IO.Path.GetExtension(sourceFile).ToLower() == ".pfs0") ||
                            (System.IO.Path.GetExtension(sourceFile).ToLower() == ".xci"))
                        {
                            PartitionFileSystem pfs;

                            if (System.IO.Path.GetExtension(sourceFile) == ".xci")
                            {
                                Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());

                                pfs = xci.OpenPartition(XciPartitionType.Secure);
                            }
                            else
                            {
                                pfs = new PartitionFileSystem(file.AsStorage());
                            }

                            foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
                            {
                                pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                                Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());

                                if (nca.Header.ContentType == NcaContentType.Program)
                                {
                                    int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);

                                    if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
                                    {
                                        patchNca = nca;
                                    }
                                    else
                                    {
                                        mainNca = nca;
                                    }
                                }
                            }
                        }
                        else if (System.IO.Path.GetExtension(sourceFile).ToLower() == ".nca")
                        {
                            mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
                        }

                        if (mainNca == null)
                        {
                            Logger.PrintError(LogClass.Application, "Extraction failed. The main NCA was not present in the selected file.");

                            Gtk.Application.Invoke(delegate
                            {
                                GtkDialog.CreateErrorDialog("Extraction failed. The main NCA was not present in the selected file.");
                            });

                            return;
                        }

                        int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);

                        IFileSystem ncaFileSystem = patchNca != null ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
                                                                     : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);

                        FileSystemClient fsClient = _virtualFileSystem.FsClient;

                        string source = DateTime.Now.ToFileTime().ToString().Substring(10);
                        string output = DateTime.Now.ToFileTime().ToString().Substring(10);

                        fsClient.Register(source.ToU8Span(), ncaFileSystem);
                        fsClient.Register(output.ToU8Span(), new LocalFileSystem(destination));

                        (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/");

                        if (!canceled)
                        {
                            if (resultCode.Value.IsFailure())
                            {
                                Logger.PrintError(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");

                                Gtk.Application.Invoke(delegate
                                {
                                    _dialog?.Dispose();

                                    GtkDialog.CreateErrorDialog("Extraction failed. Read the log file for further information.");
                                });
                            }
                            else if (resultCode.Value.IsSuccess())
                            {
                                Gtk.Application.Invoke(delegate
                                {
                                    _dialog?.Dispose();

                                    MessageDialog dialog = new MessageDialog(null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, null)
                                    {
                                        Title          = "Ryujinx - NCA Section Extractor",
                                        Icon           = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"),
                                        SecondaryText  = "Extraction has completed successfully.",
                                        WindowPosition = WindowPosition.Center
                                    };

                                    dialog.Run();
                                    dialog.Dispose();
                                });
                            }
                        }

                        fsClient.Unmount(source.ToU8Span());
                        fsClient.Unmount(output.ToU8Span());
                    }
                });

                extractorThread.Name         = "GUI.NcaSectionExtractorThread";
                extractorThread.IsBackground = true;
                extractorThread.Start();
            }
        }
Esempio n. 21
0
        // private MenuButton languageSelectorButton;


        public RoboPad(WindowType type, String[] args) : base(type)
        {
            noOfWindows++;
            SetDefaultSize(500, 500);
            Maximize();
            DeleteEvent += (sender, s) =>
            {
                if (!isChangeSaved)
                {
                    MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent,
                                                             MessageType.Warning, ButtonsType.OkCancel, "Changes Unsaved Are You Sure You Want To Exit ");
                    // Dialog dialog=new Dialog()
                    var response = dialog.Run();
                    noOfWindows--;
                    if (response == (int)Gtk.ResponseType.Ok)
                    {
                        if (noOfWindows <= 0)
                        {
                            Gtk.Application.Quit();
                        }
                    }
                    else
                    {
                        s.RetVal = true;
                    }
                    dialog.Dispose();
                }
                else
                {
                    noOfWindows--;
                    if (noOfWindows <= 0)
                    {
                        Gtk.Application.Quit();
                    }
                }
            };
            VBox vBox = new VBox();

            List <String> newTextList = new();
            var           lm          = LanguageManager.Default;

            sourceView = new();
            sourceView.Buffer.HighlightSyntax = true;
            sourceView.WrapMode        = WrapMode.Word;
            sourceView.AutoIndent      = true;
            sourceView.ShowLineNumbers = true;
            StyleSchemeManager schemeManager = StyleSchemeManager.Default;

            // StyleScheme styleScheme = schemeManager.GetScheme("pop-light");

            // sourceView.Buffer.StyleScheme = styleScheme;

            sourceView.KeyPressEvent += (o, eventArgs) =>
            {
                if (Keyval.Name(eventArgs.Event.KeyValue) == "s")
                {
                    saveFile(o, eventArgs);
                }
                else if (Keyval.Name(eventArgs.Event.KeyValue) == "S")
                {
                    saveAsFile(o, eventArgs);
                }
                else if (Keyval.Name(eventArgs.Event.KeyValue) == "o")
                {
                    openFile(o, eventArgs);
                }
            };


            headerBar = new HeaderBar();
            ScrolledWindow scrolledWindow = new ScrolledWindow();

            scrolledWindow.Add(sourceView);

            headerBar.ShowCloseButton = true;
            headerBar.Title           = "RoboPad";
            headerBarOringalText      = headerBar.Title;

            sourceView.Buffer.Changed += (sender, eventArgs) =>
            {
                headerBar.Title = "*" + headerBarOringalText;
                if (sourceView.Buffer.Text != previousText)
                {
                    isChangeSaved = false;
                }
                else
                {
                    isChangeSaved   = true;
                    headerBar.Title = headerBarOringalText;
                }
            };
            ToolButtonHandler toolbar = new ToolButtonHandler(this, sourceView);



            // Menu menu = new Menu();
            // MenuItem openItem = new RadioMenuItem("test");
            // menu.Add(openItem);
            //
            // menu.ShowAll();
            //



            PopOverMenuHandler popoverMenu = new(this);
            MenuButton         menuButton  = new MenuButton();

            menuButton.Popover = popoverMenu;
            Image image = Gtk.Image.NewFromIconName("view-more-symbolic", IconSize.LargeToolbar);

            menuButton.Image = image;
            headerBar.PackEnd(menuButton);

            Statusbar statusbar = new Statusbar();

            statusBarLabel = new("");
            statusbar.PackStart(statusBarLabel, false, false, 5);
            languageSelectorButton = new LanguageSelectorButton(sourceView);
            statusbar.PackEnd(languageSelectorButton, false, false, 5);



            // Box box = new Box(Gtk.Orientation.Vertical,2);

            Titlebar = headerBar;

            vBox.PackStart(toolbar, false, false, 0);
            vBox.PackStart(scrolledWindow, true, true, 0);
            vBox.PackStart(statusbar, false, false, 0);
            Add(vBox);

            ShowAll();

            Show();
            if (args != null)
            {
                if (args.Length >= 1)
                {
                    if (!String.IsNullOrWhiteSpace(args[0]))
                    {
                        openFileWithArgs(args[0]);
                    }
                }
            }
        }