Ejemplo n.º 1
0
        /// <summary>
        /// Registers all core ShiftOS Lua functions with their C# counterparts.
        ///
        /// This is so we don't have to expose the entire source code to the interpreter. Add new functions here.
        /// </summary>
        public void RegisterCore()
        {
            //Functions with Return Values
            mod.get_app_launcher_items = new Func <List <ApplauncherItem> >(() =>
            {
                var lst = new List <ApplauncherItem>();
                API.GetAppLauncherItems();
                foreach (var itm in API.AppLauncherItems)
                {
                    if (itm.Display == true)
                    {
                        lst.Add(itm);
                    }
                }
                return(lst);
            });
            mod.local_image      = new Func <string, Image>((filepath) => OpenLocalImage(filepath));
            mod.json_serialize   = new Func <object, string>((objectToSerialize) => Newtonsoft.Json.JsonConvert.SerializeObject(objectToSerialize));
            mod.json_unserialize = new Func <string, object>((json_string) => Newtonsoft.Json.JsonConvert.DeserializeObject(json_string));
            mod.open_image       = new Func <string, Image>((filename) => OpenImage(filename));
            mod.get_skin         = new Func <Skinning.Skin>(() =>
            {
                return(API.CurrentSkin);
            });
            mod.get_skin_images = new Func <Skinning.Images>(() =>
            {
                return(API.CurrentSkinImages);
            });
            mod.upgrades         = new Func <string, bool>((id) => GetUpgrade(id));
            mod.create_widget    = new Func <string, string, int, int, int, int, bool, Control>((type, text, x, y, width, height, dark_mode) => ConstructControl(type, text, x, y, width, height, dark_mode));
            mod.screen_get_width = new Func <int>(() =>
            {
                return(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width);
            });
            mod.screen_get_height = new Func <int>(() =>
            {
                return(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height);
            });
            mod.create_window_borderless = new Func <int, int, int, int, Form>((x, y, width, height) => CreateForm(x, y, width, height));

            mod.random = new Func <int, int, int>((min, max) =>
            {
                return(new Random().Next(min, max));
            });
            mod.color = new Func <int, int, int, Color>((r, g, b) =>
            {
                try
                {
                    return(Color.FromArgb(r, g, b));
                }
                catch (Exception ex)
                {
                    Errors.Add("Invalid color values. Values must be a minimum of 0 and a maximum of 255.");
                    return(new Color());
                }
            });
            mod.speechrec_create = new Func <SpeechListener>(() =>
            {
                return(new SpeechListener());
            });
            mod.speechrec_on_recognize = new Action <SpeechListener, string>((obj, func) =>
            {
                obj.OnRecognize += (object s, EventArgs a) =>
                {
                    mod($"{func}('{s.ToString()}')");
                };
                obj.Engine.RecognizeAsync();
            });
            mod.get_desktop_session = new Func <Form>(() =>
            {
                return(API.CurrentSession);
            });
            mod.get_icon = new Func <string, Image>((id) => API.GetIcon(id));
            mod.add_icon = new Action <string, Image>((id, img) =>
            {
                if (!API.IconRegistry.ContainsKey(id))
                {
                    API.IconRegistry.Add(id, img);
                    Skinning.Utilities.saveimages();
                }
            });
            mod.icon_exists = new Func <string, bool>((id) =>
            {
                return(API.IconRegistry.ContainsKey(id));
            });
            mod.create_window  = new Func <string, Image, int, int, Form>((title, icon, width, height) => CreateForm(title, icon, width, height));
            mod.get_codepoints = new Func <int>(() => GetCP());
            mod.buy_upgrade    = new Func <string, bool>((id) => BuyUPG(id));
            mod.time           = new Func <string>(() => API.GetTime());
            mod.encrypt        = new Func <string, string>((raw) => API.Encryption.Encrypt(raw));
            mod.decrypt        = new Func <string, string>((raw) => API.Encryption.Decrypt(raw));
            mod.fread          = new Func <string, string>((filepath) => SafeFileRead(filepath));
            mod.terminal       = new Action <string>((command) =>
            {
                var t = new Terminal();
                API.CreateForm(t, API.LoadedNames.TerminalName, API.GetIcon("Terminal"));
                t.command = command;
                t.DoCommand();
            });
            mod.fwrite = new Action <string, string>((path, contents) =>
            {
                if (path.StartsWith("/"))
                {
                    var real_path = $"{Paths.SaveRoot}{path.Replace("/", OSInfo.DirectorySeparator)}";
                    if (!Directory.Exists(real_path))
                    {
                        File.WriteAllText(real_path, contents);
                    }
                }
            });
            mod.add_menu_item       = new Func <string, MenuStrip, ToolStripMenuItem>((text, parent) => AddMenuItem(text, parent));
            mod.add_child_menu_item = new Func <string, ToolStripMenuItem, ToolStripMenuItem>((text, parent) =>
            {
                try
                {
                    var i  = new ToolStripMenuItem();
                    i.Text = text;
                    parent.DropDownItems.Add(i);
                    return(i);
                }
                catch (Exception ex)
                {
                    Errors.Add("add_child_menu_item(): Error adding child item to parent. " + ex.Message);
                    return(null);
                }
            });
            mod.set_anchor = new Action <Control, string>((ctrl, anchorstyle) => SetAnchor(ctrl, anchorstyle));

            //Standard API Functions
            mod.include              = new Action <string>((filepath) => IncludeScript(filepath));
            mod.log                  = new Action <string>((msg) => API.Log(msg));
            mod.add_codepoints       = new Action <int>((amount) => API.AddCodepoints(amount));
            mod.remove_codepoints    = new Action <int>((amount) => API.RemoveCodepoints(amount));
            mod.launch_mod           = new Action <string>((modSAA) => API.LaunchMod(Paths.SaveRoot + modSAA.Replace("/", OSInfo.DirectorySeparator)));
            mod.open_program         = new Action <string>((progname) => API.OpenProgram(progname));
            mod.close_program        = new Action <string>((progname) => API.CloseProgram(progname));
            mod.close_everything     = new Action(() => API.CloseEverything());
            mod.shutdown             = new Action(() => API.ShutDownShiftOS());
            mod.update_ui            = new Action(() => { API.UpdateWindows(); API.CurrentSession.SetupDesktop(); });
            mod.load_skin            = new Action <string>((filepath) => Skinning.Utilities.loadsknfile(filepath));
            mod.save_to_skin_file    = new Action <string>((filepath) => Skinning.Utilities.saveskintofile(filepath));
            mod.on_click             = new Action <Control, string>((ctrl, funcname) => RegClick(ctrl, funcname));
            mod.add_widget_to_window = new Action <Form, Control>((win, ctrl) => AddCtrl(win, ctrl));
            mod.open_file            = new Action <string, string>((filters, function) => OpenFile(filters, function));
            mod.panel_add_widget     = new Action <Control, Control>((ctrl, parent) =>
            {
                try {
                    var p = (Panel)parent;
                    p.Controls.Add(ctrl);
                } catch (Exception ex)
                {
                    Errors.Add(ex.Message);
                }
            });
            mod.flow_add_widget = new Action <Control, Control>((ctrl, parent) =>
            {
                try
                {
                    var p = (FlowLayoutPanel)parent;
                    p.Controls.Add(ctrl);
                }
                catch (Exception ex)
                {
                    Errors.Add(ex.Message);
                }
            });
            mod.info = new Action <string, string>((title, message) =>

                                                   API.CreateInfoboxSession(title, message, infobox.InfoboxMode.Info)

                                                   );
            mod.on_menu_item_activate = new Action <ToolStripMenuItem, string>((item, function) =>
            {
                item.Click += (object s, EventArgs a) =>
                {
                    mod($"{function}()");
                };
            });
            mod.create_timer = new Func <int, System.Windows.Forms.Timer>((interval) =>
            {
                var t      = new System.Windows.Forms.Timer();
                t.Interval = interval;
                return(t);
            });
            mod.timer_on_tick = new Action <System.Windows.Forms.Timer, string>((tmr, func) =>
            {
                try
                {
                    tmr.Tick += (object s, EventArgs a) =>
                    {
                        mod($"{func}()");
                    };
                }
                catch (Exception ex)
                {
                    Errors.Add(ex.Message);
                }
            });
            mod.add_widget_to_desktop = new Action <Control>((ctrl) => AddToDesktop(ctrl));
            mod.set_dock = new Action <Control, string>((ctrl, dstyle) =>
            {
                API.CurrentSession.Invoke(new Action(() =>
                {
                    switch (dstyle.ToLower())
                    {
                    case "fill":
                        ctrl.Dock = DockStyle.Fill;
                        break;

                    case "top":
                        ctrl.Dock = DockStyle.Top;
                        break;

                    case "bottom":
                        ctrl.Dock = DockStyle.Bottom;
                        break;

                    case "left":
                        ctrl.Dock = DockStyle.Left;
                        break;

                    case "right":
                        ctrl.Dock = DockStyle.Right;
                        break;

                    case "none":
                        ctrl.Dock = DockStyle.None;
                        break;
                    }
                }));
            });
            mod.webview_navigate = new Action <GeckoWebBrowser, string>((wv, url) => Navigate(wv, url));
            mod.open_terminal    = new Action(() =>
            {
                var t = new Terminal();
                API.CreateForm(t, API.LoadedNames.TerminalName, API.GetIcon("Terminal"));
            });
            mod.create_directory = new Action <string>((path) =>
            {
                path = $"{Paths.SaveRoot}{path.Replace("/", OSInfo.DirectorySeparator)}";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            });
            mod.exists = new Func <string, bool>((path) =>
            {
                path = $"{Paths.SaveRoot}{path.Replace("/", OSInfo.DirectorySeparator)}";
                if (Directory.Exists(path))
                {
                    return(true);
                }
                else if (File.Exists(path))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            });
            mod.notify        = new Action <string, string>((title, message) => API.CurrentSession.AddNotification(title, message));
            mod.download_file = new Action <string, string>((web_address, local) => DownloadFile(web_address, local));
            mod.on_key_down   = new Action <Control, string>((ctrl, action) => RegKeyDown(ctrl, action));
            mod.get_files     = new Func <string, List <string> >((path) => GetFiles(path));
            mod.get_folders   = new Func <string, List <string> >((path) => GetFolders(path));
            mod.zip           = new Action <string, string>((source, destination) =>
            {
                var real = $"{Paths.SaveRoot}{source.Replace("/", OSInfo.DirectorySeparator)}";
                if (Directory.Exists(real))
                {
                    var real_dest = $"{Paths.SaveRoot}{destination.Replace("/", OSInfo.DirectorySeparator)}";
                    ZipFile.CreateFromDirectory(real, real_dest);
                }
                else
                {
                    mod.info("Script Error", "Your script tried to zip up a non-existent folder.");
                }
            });
            mod.beep          = new Action <int, int>((freq, dur) => Beep(freq, dur));
            mod.color_picker += new Action <string, Color, string>((title, oldcolor, func) =>
            {
                API.CreateColorPickerSession(title, oldcolor);
                API.ColorPickerSession.FormClosing += (object s, FormClosingEventArgs a) =>
                {
                    var c = API.GetLastColorFromSession();
                    mod($"{func}(color({c.R}, {c.G}, {c.B}))");
                };
            });
            mod.info_yes_no += new Action <string, string, string>((title, message, func) =>
            {
                API.CreateInfoboxSession(title, message, infobox.InfoboxMode.YesNo);
                API.InfoboxSession.FormClosing += (object s, FormClosingEventArgs a) =>
                {
                    var res = API.GetInfoboxResult();
                    if (res == "Yes" || res == "No")
                    {
                        mod($"{func}(\"{res}\")");
                    }
                };
            });


            //Script Management
            mod.exit         = new Action(() => ExitScript());
            mod.shutdown     = new Action(() => API.ShutDownShiftOS());
            mod.toggle_unity = new Action(() => API.CurrentSession.SetUnityMode());
            mod.lua          = new Func <string, string>((luacode) =>
            {
                var li = new LuaInterpreter();
                try
                {
                    li.mod(luacode);
                    return("success");
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            });
            mod.fileskimmer_open += new Action <string, string>((filters, func) =>
            {
                API.CreateFileSkimmerSession(filters, File_Skimmer.FileSkimmerMode.Open);
                API.FileSkimmerSession.FormClosing += (object s, FormClosingEventArgs a) =>
                {
                    var res = API.GetFSResult();
                    if (res != "fail")
                    {
                        var real_path = res.Replace(Paths.SaveRoot, "/").Replace("\\", "/");
                        mod($"{func}(\"{real_path}\")");
                    }
                };
            });
            mod.fileskimmer_save += new Action <string, string>((filters, func) =>
            {
                API.CreateFileSkimmerSession(filters, File_Skimmer.FileSkimmerMode.Save);
                API.FileSkimmerSession.FormClosing += (object s, FormClosingEventArgs a) =>
                {
                    var res = API.GetFSResult();
                    if (res != "fail")
                    {
                        var real_path = res.Replace(Paths.SaveRoot, "/").Replace("\\", "/");
                        mod($"{func}(\"{real_path}\")");
                    }
                };
            });
            mod.gen_font = new Func <string, int, Font>((style, size) => {
                return(new Font(style, size));
            });


            //other
            mod.fileskimmer = new Action <string>((folder) => OpenFS(folder));
            mod.fopen       = new Action <string>((file) => OpenFile(file));
            mod.loadstring  = new Action <string>((code) => { mod(code); });

            //Multithreading
            mod.new_thread = new Func <string, Thread>((code) =>
            {
                return(new Thread(() =>
                {
                    mod(code);
                }));
            });
            mod.start_async = new Action <Thread>((t) => { t.Start(); });

            mod.add_applauncher_item = new Action <string, string>((name, lua) =>
            {
                var m  = new ModApplauncherItem();
                m.Name = name;
                m.Lua  = lua;
                File.WriteAllText(Paths.Mod_AppLauncherEntries + m.Name, JsonConvert.SerializeObject(m));
                API.UpdateWindows();
                API.CurrentSession.SetupDesktop();
            });
            mod.get_loaded_skin      = new Func <Skinning.Skin>(() => { return(API.CurrentSkin); });
            mod.reload_skin          = new Action(() => { API.CurrentSession.SetupDesktop(); API.UpdateWindows(); });
            mod.get_applauncher_item = new Func <string, ToolStripMenuItem>((name) =>
            {
                ToolStripMenuItem i = null;
                foreach (var item in API.CurrentSession.ApplicationsToolStripMenuItem.DropDownItems)
                {
                    try {
                        ToolStripMenuItem it = (ToolStripMenuItem)item;
                        if (it.Text == name)
                        {
                            i = it;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                return(i);
            });
            mod.get_menu_item = new Func <ToolStripMenuItem, string, ToolStripMenuItem>((parent, name) =>
            {
                ToolStripMenuItem i = null;
                foreach (ToolStripMenuItem item in parent.DropDownItems)
                {
                    if (item.Text == name)
                    {
                        i = item;
                    }
                }
                return(i);
            });
            GC.Collect();
        }