public override CommandFeedback Execute(string[] args)
        {
            string strSourceFolder = Environment.CurrentDirectory;

            if (args.Length > 1)
            {
                strSourceFolder = args[1];
            }

            string strDestiny = args[2];
            string strPrefix  = args[3];

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

            for (int i = 4; i < args.Length; i++)
            {
                filters.Add(args[i]);
            }

            sourceFiles = new List <FileInfo>();
            // scan all files from directory info
            ScanFolder(new DirectoryInfo(strDestiny), filters);

            RecursiveFolder(new DirectoryInfo(strSourceFolder), strDestiny, strPrefix, filters);

            ConsoleU.WriteLine("Total similar: " + similarCounter, ConsoleColor.Green);

            return(CommandFeedback.Success);
        }
Beispiel #2
0
        static void RenameMutex(string procId, string[] mutexes)
        {
            ConsoleU.WriteLine($"Process ID {procId} request to rename mutexes", Palette.Wait);
            proc = Process.GetProcessById(int.Parse(procId));

            ConsoleU.WriteLine($"Trying to rename mutexes {mutexes.Length} mutexes", Palette.Wait);
            for (int j = 0; j < mutexes.Length; j++)
            {
                string m      = mutexes[j];
                string prefix = $"({j + 1}/{mutexes.Length}) ";
                ConsoleU.WriteLine(prefix + "Trying to rename mutex: " + m, Palette.Feedback);

                for (; ;)
                {
                    if (ProcessUtil.RenameMutex(proc, m))
                    {
                        ConsoleU.WriteLine($"{prefix}Mutex rename {m}", Palette.Success);
                        break;
                    }
                    else
                    {
                        ConsoleU.WriteLine($"{prefix}Mutex {m} could not be rename", Palette.Error);
                    }
                    Thread.Sleep(250);
                }
            }
        }
        public override CommandFeedback Execute(string[] args)
        {
            if (args.Length == 1)
            {
                return(CommandFeedback.WrongNumberOfArguments);
            }

            string target       = args[1];
            string line         = args[2];
            string searchParams = args[3];

            while (line.Contains("\\n"))
            {
                line = line.Replace("\\n", "\n");
            }

            if (!Directory.Exists(target))
            {
                return(CommandFeedback.Error);
            }

            ConsoleU.WriteLine("Searching directory...", Palette.Wait);

            // target is a directory
            DirectoryInfo dir = new DirectoryInfo(target);

            FileInfo[] files = dir.GetFiles(searchParams);
            ConsoleU.WriteLine($"Found { files.Length } files. Would you like to write to the top of them?", Palette.Question);

            int changed = 0;
            int failed  = 0;

            if (consoleManager.InputYesNo())
            {
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo file = files[i];
                    try
                    {
                        string readAll = File.ReadAllText(file.FullName);
                        readAll += line;
                        File.Delete(file.FullName);
                        File.WriteAllText(file.FullName, readAll);
                        changed++;
                    }
                    catch
                    {
                        ConsoleU.WriteLine($"Failed writing to { file.Name } ", Palette.Error);
                        failed++;
                    }
                }
            }

            ConsoleU.WriteLine($"Changed { changed } files", Palette.Success);
            ConsoleU.WriteLine($"Failed to change { failed } files", failed == 0 ? Palette.Success : Palette.Error);
            ConsoleS.ReadLine();

            return(CommandFeedback.Success);
        }
        private void treeView_dir_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
#if print
            ConsoleU.writeLine(String.Format("node selected. . {0}", e.Node.FullPath), ConsoleU.Level.Info);
#endif
            if (e.Node.Text == REMOTE_MENU)
            {
                dataGridView(); //load dsRandomXml from xml and Bound to dgb
                groupbox();

                if (sign == "on")
                {
                    dataGridView1.Visible = true;
                    groupBox1.Visible     = true;
                }
                else if (sign == "off")
                {
                    if (mSpSlot != null)
                    {
                        dataGridView1.Visible = true;
                        groupBox1.Visible     = true;

                        mRemote                 = new gf_remote(mSpSlot);// open remote form
                        mRemote.Owner           = this;
                        mRemote.Move           += new EventHandler(subFormMove);
                        mRemote.mMainFormTrans += new mainFormTrans(remoteEventReceive); //this is a delegate in order to  close subForm
                        mRemote.Show();
                        sign = "on";
                        this.AddOwnedForm(mRemote);
                        mDockRemote           = new DockU(this);//DockU
                        mDockRemote.isEnabled = true;
                        mDockRemote.position  = DockU.Position.MiddleRight;
                        mDockRemote.process(mRemote);
                        serialToolStripMenuItem.Enabled = false;
                    }
                    else
                    {
                        ConsoleU.writeLine(String.Format("No choice of serial"), ConsoleU.Level.Error);
                        treeView_dir.SelectedNode = null;
                        dataGridView1.Visible     = false;
                        groupBox1.Visible         = false;
                    }
                }
                else
                {
                    dataGridView1.Visible = false;
                    groupBox1.Visible     = false;
                }
            }
            else
            {
                dataGridView1.Visible = false;
                groupBox1.Visible     = false;
            }
        }
        public override CommandFeedback Execute(string[] args)
        {
            if (args.Length == 1)
            {
                return(CommandFeedback.WrongNumberOfArguments);
            }

            string target = args[1];

            if (!Path.IsPathRooted(target))
            {
                // relative path
                string currentDir = Environment.CurrentDirectory;
                target = Path.Combine(currentDir, target);
            }

            if (!File.Exists(target))
            {
                Console.WriteLine($"File not found: {target}");
                return(CommandFeedback.Error);
            }

            // rename the source file to backup
            string dir        = Path.GetDirectoryName(target);
            string fileName   = Path.GetFileNameWithoutExtension(target);
            string sourceFile = Path.Combine(dir, fileName + "_Backup.m4a");

            File.Move(target, sourceFile);

            string startArgs = $"ffmpeg -i \"{sourceFile}\" -acodec copy -movflags faststart \"{target}\"";

            int exitCode;

            CmdUtil.ExecuteCommand("", out exitCode, startArgs);

            bool makeBackup = false;

            if (File.Exists(target))
            {
                if (!makeBackup)
                {
                    File.Delete(sourceFile);
                }
                ConsoleU.WriteLine($"Okay", Palette.Success);
            }
            else
            {
                ConsoleU.WriteLine($"FFMPEG failed with code {exitCode}", Palette.Error);
                return(CommandFeedback.Error);
            }

            return(CommandFeedback.Success);
        }
Beispiel #6
0
        public override CommandFeedback Execute(string[] args)
        {
            if (args.Length == 1)
            {
                return(CommandFeedback.WrongNumberOfArguments);
            }

            string target = args[1];

            if (Directory.Exists(target))
            {
                ConsoleU.WriteLine("Searching directory...", Palette.Wait);

                // target is a directory
                DirectoryInfo dir  = new DirectoryInfo(target);
                List <string> dirs = new List <string>();
                RecursiveSearch(dir, dirs);

                if (dirs.Count == 0)
                {
                    ConsoleU.WriteLine($"Nothing to delete", Palette.Feedback);
                    return(CommandFeedback.Success);
                }
                ConsoleU.WriteLine($"Found { dirs.Count } empty directories. Would you like to delete them?", Palette.Question);

                int deleted = 0;
                int failed  = 0;
                if (consoleManager.InputYesNo())
                {
                    for (int i = 0; i < dirs.Count; i++)
                    {
                        string directory = dirs[i];
                        try {
                            Directory.Delete(directory);
                            deleted++;
                        } catch {
                            ConsoleU.WriteLine($"Failed deleting { directory } ", Palette.Error);
                            failed++;
                        }
                    }
                }

                ConsoleU.WriteLine($"Deleted { deleted } files", Palette.Success);
                ConsoleU.WriteLine($"Failed to delete { failed } files", failed == 0 ? Palette.Success : Palette.Error);
            }
            else
            {
                // target is a file/doesnt exist
            }


            return(CommandFeedback.Success);
        }
        public override CommandFeedback Execute(string[] args)
        {
            if (args.Length == 1)
            {
                return(CommandFeedback.WrongNumberOfArguments);
            }

            string target = args[1];

            if (!File.Exists(target))
            {
                return(CommandFeedback.Error);
            }

            string startTime   = args[2];
            string cutDuration = args[3];


            // rename the source file to backup
            string dir        = Path.GetDirectoryName(target);
            string fileName   = Path.GetFileNameWithoutExtension(target);
            string sourceFile = Path.Combine(dir, fileName + "_Backup.m4a");

            File.Move(target, sourceFile);

            //ffmpeg - ss 1:01:42 - i c:\Data\temp\in.m4a - vn - c copy - t 1:00:00 out.m4a

            //The first time(1:01:42) is the start time of the cut.
            //-vn means that only the audio stream is copied from the file.
            //The second time(1:00:00) is the duration of the cut.It can be longer then the length of the whole file.
            string startArgs = $"ffmpeg -ss {startTime} -i \"{sourceFile}\" -vn -c copy -t {cutDuration} \"{target}\"";

            int exitCode;

            CmdUtil.ExecuteCommand("", out exitCode, startArgs);

            bool makeBackup = false;

            if (File.Exists(target))
            {
                if (!makeBackup)
                {
                    File.Delete(sourceFile);
                }
                ConsoleU.WriteLine($"Okay", Palette.Success);
            }
            else
            {
                ConsoleU.WriteLine($"Failed", Palette.Error);
            }

            return(CommandFeedback.Success);
        }
        private void debugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;

            menuItem.Checked = !menuItem.Checked;
            if (menuItem.Checked)
            {
                ConsoleU.createConsole();
            }
            else
            {
                ConsoleU.releaseConsole();
            }
        }
        //Int32 mBytesRead=0;
        //Byte[] mReadBuffer = new Byte[10];
        void dataReceived(System.Object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //received data
        {
            System.IO.Ports.SerialPort sp = (System.IO.Ports.SerialPort)sender;
            string indata = sp.ReadExisting();

            //if (sp.BytesToRead <= 0)
            //{
            //    ConsoleU.writeLine("empty trigger", ConsoleU.Level.Warning);
            //    return;
            //}
            //mBytesRead += sp.Read(mReadBuffer, mBytesRead, sp.BytesToRead);
            //ConsoleU.writeLine(string.Format("Data Received: {0}", System.Text.Encoding.Default.GetString (mReadBuffer)), ConsoleU.Level.Info);
            ConsoleU.writeLine(string.Format("Data Received: {0}", indata), ConsoleU.Level.Info);
        }
Beispiel #10
0
        public bool InputYesNo(bool silent = true)
        {
            ConsoleU.WriteLine("Yes/No", Palette.Question);
            if (silentMode)
            {
                // still shows up that we were asking the user a question
                ConsoleU.WriteLine(silent ? "Yes" : "No", Palette.Question);
                ConsoleU.WriteLine("yes");
                return(silent);
            }

            string yesno = ConsoleU.ReadLine().ToLower();

            return(yesno.StartsWith("y"));
        }
        void loadRemoteTree()
        {
            treeView_dir.Nodes.Clear();
            DataTable dtTemp = new DataTable();

            String printInfo = "binding tree node... ...";

            ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning);

            DataSet ds = new DataSet();

            /*dir=String.Format("{0}/{1}/{2}",
             * Directory.GetCurrentDirectory(), FILEPATH, CTRLNAME);*/
            dir = String.Format("{0}/{1}/{2}",
                                Application.StartupPath, FILEPATH, TREENAME);

            String fileExtension = System.IO.Path.GetExtension(dir);

            if (fileExtension != ".xml" || !System.IO.File.Exists(dir))
            {
                ConsoleU.writeLine("this file is not xml or path error,please select again!", ConsoleU.Level.Warning);
            }
            ds.ReadXml(dir);
            dtTemp = ds.Tables[DIRTREE];//this is Tree xml file

            if (dtTemp == null)
            {
                printInfo = "Cannot find node,please try again..."; ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning); return;
            }
            if (dtTemp.Rows == null)
            {
                printInfo = "Cannot find node rows,please try again..."; ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning); return;
            }

            Int32 index = 0;

            foreach (DataRow row in dtTemp.Rows)
            {
                if (Int32.Parse(row[PARENT].ToString()) == 0)
                {
                    treeView_dir.Nodes.Add(row[CURRENT].ToString(), row[CURRENTNMAE].ToString());
                    AddTreeNode(dtTemp.Rows, row[CURRENT].ToString(), treeView_dir.Nodes[index++]);
                }
            }
            treeView_dir.Nodes[0].Expand();
            treeView_dir.Nodes[0].ImageIndex = 0;
            treeView_dir.SelectedNode        = null;
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            ConsoleManager console = new ConsoleManager();

            console.Init();
            ConsoleU.WriteLine("DistroLucas's FileUtils v" + FileUtilsGlobals.DisplayVersion.ToString("F2", CultureInfo.InvariantCulture), ConsoleColor.White);

            console.SearchFromLoadedAssemblies();

            if (args.Length > 0)
            {
                console.ExecuteCommand(args);
            }

            console.Run();
        }
Beispiel #13
0
        public void ChecaInput()
        {
#if UNITY
            if (ConsoleU.KeyAvailable)
            {
                teclaApertada = ConsoleU.ReadKey(true);
            }
#else
            if (Console.KeyAvailable)
            {
                teclaApertada = Console.ReadKey(true).Key;
            }
#endif
            else
            {
                teclaApertada = 0;
            }
        }
Beispiel #14
0
        public void Run()
        {
            Console.WriteLine();
            ConsoleU.WriteLine($"Server running in port {Port}", ConsoleColor.Cyan);

            string startFolder = AssemblyUtil.GetStartFolder();

            ConsoleU.WriteLine($"Start folder: {startFolder}", ConsoleColor.Green);

            ConsoleU.WriteLine($"Path provided: {path}", ConsoleColor.Green);
            string[] files = Directory.GetFiles(path);
            for (int i = 0; i < files.Length; i++)
            {
                ConsoleU.WriteLine($"Files: {files[i]}", ConsoleColor.Green);
            }

            httpServer.Listen();
        }
Beispiel #15
0
 //private void timer1_Tick(object sender, EventArgs e)
 private void LoopRandom()
 {
     while (true)
     {
         if (gf_main.testBegin)      //click test button
         {
             if (gf_main.randomOrNo) //click random button
             {
                 ranID = ran.Next(cc_control.dtEvent.Rows.Count);
                 if (cc_control.dtEvent.Rows[ranID][gf_main.CTRLLINE].ToString() != "")//avoid empty event
                 {
                     ConsoleU.writeLine(String.Format("you click: {0} button, \"{1}\"", cc_control.dtEvent.Rows[ranID][gf_main.CTRLEVENTNAME].ToString(), cc_control.dtEvent.Rows[ranID][gf_main.CTRLLINE].ToString()), ConsoleU.Level.Info);
                     ProtocolObject.remoteWrite(SocProtocol.Drive.remote, System.Text.Encoding.ASCII.GetBytes(cc_control.dtEvent.Rows[ranID][gf_main.CTRLLINE].ToString()));
                     System.Threading.Thread.Sleep(2000);
                 }
             }
             else
             {
                 for (int i = gf_main.dgvIndex; i < gf_main.dsRandomXml.Tables[0].Rows.Count; i++)
                 {
                     string[] random = gf_main.dsRandomXml.Tables[0].Rows[i]["serialize_Text"].ToString().Split(',');
                     foreach (string mRandom in random)
                     {
                         for (int index = 0; index < cc_control.dtEvent.Rows.Count; index++)
                         {
                             if (!gf_main.testBegin)//click test button
                             {
                                 break;
                             }
                             if (mRandom == cc_control.dtEvent.Rows[index][gf_main.CTRLEVENTNAME].ToString())
                             {
                                 ConsoleU.writeLine(String.Format("you click: {0} button, \"{1}\"", cc_control.dtEvent.Rows[index][gf_main.CTRLEVENTNAME].ToString(), cc_control.dtEvent.Rows[index][gf_main.CTRLLINE].ToString()), ConsoleU.Level.Info);
                                 ProtocolObject.remoteWrite(SocProtocol.Drive.remote, System.Text.Encoding.ASCII.GetBytes(cc_control.dtEvent.Rows[index][gf_main.CTRLLINE].ToString()));
                                 System.Threading.Thread.Sleep(2000);
                             }
                         }
                     }
                 }
             }
         }
         Thread.Sleep(1000);
     }
 }
        public void Renderizacanvas()
        {
#if UNITY
            ConsoleU.Clear();
#else
            Console.Clear();
#endif
            buffer = string.Empty;
            for (int y = 0; y < altura; y++)
            {
                for (int x = 0; x < largura; x++)
                {
                    buffer += canvas[x, y];
                }

                buffer += "\n";
            }
            Console.Write(buffer);
        }
 private void ServerThread(object state)
 {
     while (this.IsActive)
     {
         if (Debug)
         {
             TcpClient s      = this.Listener.AcceptTcpClient();
             Thread    thread = new Thread(() => {
                 if (DebugLock)
                 {
                     lock (DebugLocker) {
                         this.Processor.HandleClient(s);
                     }
                 }
                 else
                 {
                     this.Processor.HandleClient(s);
                 }
             });
             thread.Start();
             Thread.Sleep(1);
         }
         else
         {
             try {
                 TcpClient s      = this.Listener.AcceptTcpClient();
                 Thread    thread = new Thread(() => {
                     try {
                         this.Processor.HandleClient(s);
                     } catch (Exception ex) {
                         ConsoleU.WriteLine("Exception " + ex, ConsoleColor.Red);
                     }
                 });
                 thread.Start();
                 Thread.Sleep(1);
             } catch (Exception ex) {
                 ConsoleU.WriteLine("Exception " + ex, ConsoleColor.Red);
             }
         }
     }
 }
Beispiel #18
0
        public override CommandFeedback Execute(string[] args)
        {
            if (args.Length == 1)
            {
                ConsoleU.WriteLine(Help, Palette.Feedback);
                return(CommandFeedback.Success);
            }

            string         target = args[1];
            ConsoleCommand cmd    = consoleManager.GetCommand(target);

            if (cmd != null)
            {
                ConsoleU.WriteLine(cmd.Help, Palette.Help);
            }
            else
            {
                ConsoleU.WriteLine("Unknown command", Palette.Error);
            }

            return(CommandFeedback.Success);
        }
Beispiel #19
0
        private void button_Click(object sender, EventArgs e)
        {
            Button btn_Click = (Button)sender;

            if (gf_main.serializeSigh == "serialize")
            {
                gf_serialize a = mMainFormTrans("serializeFrm");
                a.remoteEventReceive(btn_Click.Text);
                return;
            }

            for (int i = 0; i < cc_control.dtEvent.Rows.Count; i++)
            {
                if (cc_control.dtEvent.Rows[i][gf_main.CTRLEVENTNAME].ToString() == btn_Click.Text)
                {
                    ConsoleU.writeLine(String.Format("you click: {0} button, \"{1}\"", btn_Click.Text, cc_control.dtEvent.Rows[i][gf_main.CTRLLINE].ToString()), ConsoleU.Level.Info);
                    ProtocolObject.remoteWrite(SocProtocol.Drive.remote, System.Text.Encoding.ASCII.GetBytes(cc_control.dtEvent.Rows[i][gf_main.CTRLLINE].ToString()));

                    break;
                }
            }
        }
Beispiel #20
0
        static void StartGame(string path, string args = "", string workingDir = null)
        {
            if (!Path.IsPathRooted(path))
            {
                string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                path = Path.Combine(root, path);
            }

            ProcessStartInfo startInfo;

            startInfo           = new ProcessStartInfo();
            startInfo.FileName  = path;
            startInfo.Arguments = args;
            if (!string.IsNullOrWhiteSpace(workingDir))
            {
                startInfo.WorkingDirectory = workingDir;
            }

            proc = Process.Start(startInfo);
            ConsoleU.WriteLine("Game started, process ID:" + proc.Id, Palette.Success);
            WriteToDataFile(path, proc.Id.ToString());
        }
Beispiel #21
0
        static void StartGame(string path, string args = "", string workingDir = null)
        {
            if (!Path.IsPathRooted(path))
            {
                string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                path = Path.Combine(root, path);
            }

            int tri = 0;
            ProcessStartInfo startInfo;

            startInfo           = new ProcessStartInfo();
            startInfo.FileName  = path;
            startInfo.Arguments = args;
            if (!string.IsNullOrWhiteSpace(workingDir))
            {
                startInfo.WorkingDirectory = workingDir;
            }

#if RELEASE
            try
#endif
            {
                proc = Process.Start(startInfo);
                ConsoleU.WriteLine("Game started, process ID:" + proc.Id, Palette.Success);
            }
#if RELEASE
            catch
            {
                tri++;
                if (tri < tries)
                {
                    ConsoleU.WriteLine("Failed to start process. Retrying...");
                    StartGame(path, args);
                }
            }
#endif
        }
Beispiel #22
0
        public void ExecuteCommand(string[] sep)
        {
            if (sep.Length == 0)
            {
                return;
            }

            string         first = sep[0];
            ConsoleCommand cmd;

            if (!commands.TryGetValue(first, out cmd))
            {
                ConsoleU.WriteLine("Unknown command", Palette.Error);
                return;
            }

            CommandFeedback feedback = cmd.Execute(sep);

            if (feedback != CommandFeedback.Success)
            {
                ConsoleU.WriteLine(feedback.ToString(), Palette.Error);
            }
        }
        public static string serializeSigh = ""; //为了区分是命令还是添加修改序列化
        public gf_main(string[] args)
        {
            InitializeComponent();
#if printf
            Text = String.Format("{0} v{1} < build {2} >", Text, gf_main.VERSION, DateTime.Now.ToString());
            ConsoleU.writeLine(Text, ConsoleU.Level.Warning);

            string mArgs = String.Empty;
            foreach (string arg in args)
            {
                mArgs += arg + " ";
            }
            mArgs = mArgs.Trim();

            ConsoleU.writeLine(String.Format("args = \"{0}\"", mArgs), ConsoleU.Level.Warning);
            ConsoleU.writeLine(String.Format("work dir = \"{0}\"", Application.StartupPath),
                               ConsoleU.Level.Warning);
#endif

            debugToolStripMenuItem.Checked = true;//for debug initialize selected

            toolStripStatusLabel1.Text = String.Format(" {0} {1} v{2} < build {2} >", "     ", Text, VERSION, DateTime.Now.ToString());
        }
        static void Main(string[] args)
        {
            #if _DEBUG
            //Directory::SetCurrentDirectory(String::Format("{0}/../Release", AppDomain.CurrentDomain->BaseDirectory));
             Directory.SetCurrentDirectory(String.Format("{0}/../Release",AppDomain.CurrentDomain.BaseDirectory);
#else
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
#endif

//#ifndef _DEBUG
        //try {
//#endif
		// check multiple instances
		if (!ProcessU.multiple(args)) {
			System.Environment.Exit(0);
		}

		// check open console
		if (Array.IndexOf(args, "-debug") >= 0) {
			// create but not log
			ConsoleU.createConsole();
			ConsoleU.hide();
		} 

		// check log file
		if (Array.IndexOf(args, "-log") >= 0) {			
			ConsoleU.createConsole(true);
			ConsoleU.hide();
		}


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new gf_main(args));
            //Application.Run(new soc_remote.gf_remote());

        }
Beispiel #25
0
        static void QueryMutex(string procId, string[] mutexes)
        {
            Log.WriteLine($"Process ID {procId} request to be queried for mutexes", Palette.Wait);
            proc = Process.GetProcessById(int.Parse(procId));

            ConsoleU.WriteLine($"Trying to query for any mutex's existance", Palette.Wait);

            bool[] existence = new bool[mutexes.Length];
            for (int j = 0; j < mutexes.Length; j++)
            {
                string m      = mutexes[j];
                string prefix = $"({j + 1}/{mutexes.Length}) ";
                ConsoleU.WriteLine($"{prefix}Trying to scan if mutex exists: {m}", Palette.Feedback);

                bool exists = ProcessUtil.MutexExists(proc, m);
                Log.WriteLine(exists);
            }
            Thread.Sleep(250);

            string json = JsonConvert.SerializeObject(existence);

            // no game path, save to startgame directory/Nucleus folder
            WriteToDataFile(Assembly.GetEntryAssembly().Location, json);
        }
Beispiel #26
0
        static void StartGame(string path, string args = "", string workingDir = null)
        {
            System.IO.Stream str = new System.IO.MemoryStream();
            //GenericGameInfo gen = new GenericGameInfo(null, null, str);
            bool regMethod = false;

            if (!Path.IsPathRooted(path))
            {
                string root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                path = Path.Combine(root, path);
            }

            try
            {
                //proc = Process.Start(startInfo);
                //string currDir = Directory.GetCurrentDirectory();

                // This works even if the current directory is set elsewhere.
                string currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                //bool is64 = EasyHook.RemoteHooking.IsX64Process((int)pi.dwProcessId);
                //if (Is64Bit(path) == true)
                //{
                //    gameIs64 = true;
                //}
                //bool is64 = EasyHook.RemoteHooking.IsX64Process((int)pi.dwProcessId);

                IntPtr envPtr         = IntPtr.Zero;
                uint   pCreationFlags = 0;

                if (useNucleusEnvironment && !(useStartupHooks && (isHook || renameMutex || setWindow || blockRaw || createSingle)))
                {
                    Log("Setting up Nucleus environment");
                    var         sb      = new StringBuilder();
                    IDictionary envVars = Environment.GetEnvironmentVariables();
                    //var username = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).Replace(@"C:\Users\", "");
                    string username = WindowsIdentity.GetCurrent().Name.Split('\\')[1];
                    envVars["USERPROFILE"]  = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}";
                    envVars["HOMEPATH"]     = $@"\Users\{username}\NucleusCoop\{playerNick}";
                    envVars["APPDATA"]      = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}\AppData\Roaming";
                    envVars["LOCALAPPDATA"] = $@"{NucleusEnvironmentRoot}\NucleusCoop\{playerNick}\AppData\Local";

                    //Some games will crash if the directories don't exist
                    Directory.CreateDirectory($@"{NucleusEnvironmentRoot}\NucleusCoop");
                    Directory.CreateDirectory(envVars["USERPROFILE"].ToString());
                    Directory.CreateDirectory(Path.Combine(envVars["USERPROFILE"].ToString(), "Documents"));
                    Directory.CreateDirectory(envVars["APPDATA"].ToString());
                    Directory.CreateDirectory(envVars["LOCALAPPDATA"].ToString());

                    Directory.CreateDirectory(Path.GetDirectoryName(DocumentsRoot) + $@"\NucleusCoop\{playerNick}\Documents");

                    if (useDocs)
                    {
                        if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"utils\backup\User Shell Folders.reg")))
                        {
                            //string mydocPath = key.GetValue("Personal").ToString();
                            ExportRegistry(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"utils\backup\User Shell Folders.reg"));
                        }

                        RegistryKey dkey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", true);
                        dkey.SetValue("Personal", Path.GetDirectoryName(DocumentsRoot) + $@"\NucleusCoop\{playerNick}\Documents", (RegistryValueKind)(int)RegType.ExpandString);
                    }


                    foreach (object envVarKey in envVars.Keys)
                    {
                        if (envVarKey != null)
                        {
                            string key   = envVarKey.ToString();
                            string value = envVars[envVarKey].ToString();

                            sb.Append(key);
                            sb.Append("=");
                            sb.Append(value);
                            sb.Append("\0");
                        }
                    }

                    sb.Append("\0");

                    byte[] envBytes = Encoding.Unicode.GetBytes(sb.ToString());
                    envPtr = Marshal.AllocHGlobal(envBytes.Length);
                    Marshal.Copy(envBytes, 0, envPtr, envBytes.Length);
                }

                pCreationFlags += (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;

                STARTUPINFO startup = new STARTUPINFO();
                startup.cb = Marshal.SizeOf(startup);

                Thread.Sleep(1000);

                if (useStartupHooks && (isHook || renameMutex || setWindow || blockRaw || createSingle))
                {
                    Log("Starting game and injecting start up hooks via Nucleus.Inject");

                    bool?is64_n = Is64Bit(path);

                    if (!is64_n.HasValue)
                    {
                        Log(string.Format("ERROR - Machine type {0} not implemented", GetDllMachineType(path)));
                        return;
                    }

                    bool is64 = is64_n.Value;

                    //PROCESS_INFORMATION procInfo = new PROCESS_INFORMATION();

                    Process[] gameProcs     = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path));
                    bool      alreadyExists = false;
                    if (gameProcs.Length > 0)
                    {
                        foreach (Process gameProc in gameProcs)
                        {
                            if (gameProc.GetMainModuleFileName().ToLower() == path.ToLower())
                            {
                                Log("Process with this path is already running! Skipping creating a new process");
                                pOutPID       = (uint)gameProc.Id;
                                alreadyExists = true;
                            }
                        }
                    }

                    if (!alreadyExists)
                    {
                        try
                        {
                            //if(useNucleusEnvironment)
                            //{
                            //    bool success = CreateProcess(null, path + " " + args, IntPtr.Zero, IntPtr.Zero, false, (uint)ProcessCreationFlags.CREATE_SUSPENDED | (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT, envPtr, Path.GetDirectoryName(path), ref startup, out PROCESS_INFORMATION processInformation);
                            //    if (!success)
                            //    {
                            //        Log(string.Format("ERROR - CreateProcess failed - startGamePath: {0}, startArgs: {1}, dirpath: {2}", path, args, Path.GetDirectoryName(path)));
                            //        return;
                            //    }

                            //    procInfo = processInformation;
                            //    pOutPID = (uint)processInformation.dwProcessId;
                            //}

                            //Thread.Sleep(1000);

                            string           injectorPath = Path.Combine(currDir, $"Nucleus.IJ{(is64 ? "x64" : "x86")}.exe");
                            ProcessStartInfo injstartInfo = new ProcessStartInfo();
                            injstartInfo.FileName = injectorPath;
                            object[] injargs = new object[]
                            {
                                0,                                            // Tier 0 : start up hook
                                path,                                         // EXE path
                                args,                                         // Command line arguments. TODO: these args should be converted to base64 to prevent any special characters e.g. " breaking the injargs
                                pCreationFlags,                               // Process creation flags
                                0,                                            // InInjectionOptions (EasyHook)
                                Path.Combine(currDir, "Nucleus.SHook32.dll"), // lib path 32
                                Path.Combine(currDir, "Nucleus.SHook64.dll"), // lib path 64
                                isHook,                                       // Window hooks
                                renameMutex,                                  // Renames mutexes/semaphores/events hook
                                mutexToRename,
                                setWindow,                                    // Set window hook
                                isDebug,
                                nucleusFolderPath,
                                blockRaw,
                                useNucleusEnvironment,
                                playerNick,
                                createSingle,
                                rawHid,
                                width,
                                height,
                                posx,
                                posy,
                                DocumentsRoot,
                                useDocs
                            };

                            var sbArgs = new StringBuilder();
                            foreach (object arg in injargs)
                            {
                                //Converting to base64 prevents characters like " or \ breaking the arguments
                                string arg64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(arg.ToString()));

                                sbArgs.Append(" \"");
                                sbArgs.Append(arg64);
                                sbArgs.Append("\"");
                            }

                            string arguments = sbArgs.ToString();
                            injstartInfo.Arguments = arguments;
                            //injstartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            //injstartInfo.CreateNoWindow = true;
                            injstartInfo.UseShellExecute        = false;
                            injstartInfo.RedirectStandardOutput = true;
                            injstartInfo.RedirectStandardInput  = true;

                            Process injectProc = Process.Start(injstartInfo);
                            injectProc.OutputDataReceived += proc_OutputDataReceived;
                            injectProc.BeginOutputReadLine();
                            injectProc.WaitForExit();
                        }
                        catch (Exception ex)
                        {
                            Log(string.Format("ERROR - {0}", ex.Message));
                        }

                        if (injectFailed)
                        {
                            injectFailed = false;
                            throw new Exception("Failed to create and/or inject start up hook dll. " + tri + " of 2.");
                        }

                        //if(useNucleusEnvironment)
                        //{
                        //    ResumeThread(procInfo.hThread);
                        //}

                        Thread.Sleep(1000);
                    }
                }
                else // regular method (no hooks)
                {
                    Log("Starting game via regular process start method (no start up hooks enabled)");


                    bool success = CreateProcess(null, path + " " + args, IntPtr.Zero, IntPtr.Zero, false, (uint)ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT, envPtr, Path.GetDirectoryName(path), ref startup, out PROCESS_INFORMATION processInformation);
                    if (!success)
                    {
                        Log(string.Format("ERROR - CreateProcess failed - startGamePath: {0}, startArgs: {1}, dirpath: {2}", path, args, Path.GetDirectoryName(path)));
                        return;
                    }

                    pOutPID = (uint)processInformation.dwProcessId;
                    proc    = Process.GetProcessById((int)pOutPID);
                    //pOutPID = proc.Id;
                    regMethod = true;
                }

                Thread.Sleep(1000);

                while (pOutPID == 0)
                {
                    Thread.Sleep(50);
                }

                bool isRunning = Process.GetProcesses().Any(x => x.Id == (int)pOutPID);
                bool foundProc = false;
                if (!isRunning || (isRunning && Process.GetProcessById((int)pOutPID).ProcessName.ToLower() != Path.GetFileNameWithoutExtension(path).ToLower()))
                {
                    if (isRunning)
                    {
                        Log("Process ID " + pOutPID + " exists but does not match expected process name. Attempting to resolve.");
                    }
                    else
                    {
                        Log("Process ID " + pOutPID + " doesn't currently exist. Seeing if there is a process running by its path");
                    }

                    Process[] gameProcs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(path));

                    if (gameProcs.Length > 0)
                    {
                        foreach (Process gameProc in gameProcs)
                        {
                            if (gameProc.GetMainModuleFileName().ToLower() == path.ToLower())
                            {
                                Log("Process ID changed to " + pOutPID);
                                foundProc = true;
                                isRunning = true;
                                pOutPID   = (uint)gameProc.Id;
                            }
                        }
                        if (!foundProc)
                        {
                            Log("Could not find process by its path");
                        }
                    }
                    else
                    {
                        Log("Could not find any matching process names");
                    }
                }
                else
                {
                    Log("Process ID: " + pOutPID);
                    if (Process.GetProcessById((int)pOutPID).GetMainModuleFileName().ToLower() == path.ToLower())
                    {
                        foundProc = true;
                        isRunning = true;
                    }
                }

                //Thread.Sleep(100);

                //if (proc != null && proc.Threads[0].ThreadState != System.Diagnostics.ThreadState.Running)
                if (!isRunning && !foundProc)
                {
                    Log("Process with ID " + pOutPID + " is still not currently running. Checking every 50 miliseconds for 10 seconds to see if process is running yet.");
                    for (int times = 0; times < 200; times++)
                    {
                        Thread.Sleep(50);
                        isRunning = Process.GetProcesses().Any(x => x.Id == (int)pOutPID);
                        if (isRunning)
                        {
                            Log("Attempt #" + times + " - Process is now running");
                            proc = Process.GetProcessById((int)pOutPID);
                            break;
                        }
                        if (times == 199 && !isRunning)
                        {
                            Log(string.Format("ERROR - Process with an id of {0} is not running after 10 seconds. Aborting.", pOutPID));

                            throw new Exception(string.Format("ERROR - Process with an id of {0} is not running after 10 seconds. Aborting.", pOutPID));
                        }
                    }
                }

                ConsoleU.WriteLine("Game started, process ID:" + pOutPID /*Marshal.ReadInt32(pid)*/ /*proc.Id*/ /*(int)pi.dwProcessId*/, Palette.Success);
                if (isDebug)
                {
                    //if (regMethod)
                    //{
                    //Thread.Sleep(100);
                    Log(string.Format("Game started, process ID: {0}", pOutPID));
                    //}
                    //else
                    //{
                    //    Thread.Sleep(100);
                    //    Log(string.Format("Game started, process ID: {0}", pOutPID));
                    //}
                }
            }

            catch (Exception ex)
            {
                tri++;
                if (tri < tries)
                {
                    if (!ex.Message.Contains("debug-log"))
                    {
                        Log(string.Format("ERROR - Failed to start process. EXCEPTION: {0} STACKTRACE: {1}", ex.Message, ex.StackTrace));
                        Console.WriteLine("Failed to start process. Retrying...");
                    }
                    StartGame(path, args);
                }
                else
                {
                    MessageBox.Show("Nucleus was unable to launch and/or find the proper process for this instance. Please close Nucleus and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #27
0
        public override CommandFeedback Execute(string[] args)
        {
            string strIP       = args[1];
            string audioOutput = args[2];

            NAudio.CoreAudioApi.MMDeviceEnumerator enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator();
            var audioDevices = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.Active);
            var audioDevice  = audioDevices.FirstOrDefault(c => c.FriendlyName.ToLower().Contains(audioOutput));

            if (audioDevice == null)
            {
                ConsoleU.WriteLine("Failed to locate audio device", ConsoleColor.Red);
                return(CommandFeedback.Error);
            }

            //WasapiLoopbackCapture capture = new WasapiLoopbackCapture();
            //capture.DataAvailable += (object s, WaveInEventArgs waveArgs) => {

            //    //writer.Write(a.Buffer, 0, a.BytesRecorded);
            //    //if (writer.Position > capture.WaveFormat.AverageBytesPerSecond * 20) {
            //    //    capture.StopRecording();
            //    //}
            //};

            Device device = new Device(strIP);

            AsyncHelpers.RunSync(device.Connect);

            int lastBrightness = 1;

            AsyncHelpers.RunSync(() => {
                for (; ;)
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1001));

                    float peakValue   = audioDevice.AudioMeterInformation.MasterPeakValue;
                    int peakValueCent = (int)(peakValue * 120);
                    int peakValueBars = (int)(peakValue * 120);
                    int peakValueInt  = (int)(peakValue * 200.0f);

                    peakValueCent = MathUtil.Clamp(peakValueCent, 1, 100);

                    //Math.Log()

                    //device.SetBrightness((int)(audioDevice.AudioMeterInformation.MasterPeakValue * 200));

                    //AsyncHelpers.RunSync(() => {
                    //    return device.SetRGBColor(peakValueInt / 2, peakValueInt / 2, peakValueInt);
                    //});

                    if (lastBrightness != peakValueCent)
                    {
                        lastBrightness = peakValueCent;
                        AsyncHelpers.RunSync(() => {
                            return(device.SetBrightness(peakValueCent));
                        });
                    }

                    string strRepeat = StringUtil.RepeatCharacter('■', peakValueBars);
                    Console.WriteLine($"({peakValueCent}) {strRepeat}");
                    //Console.WriteLine(peakValueInt);
                }
            });

            device.Disconnect();

            return(CommandFeedback.Success);
        }
        protected virtual HttpResponse RouteRequest(Stream inputStream, Stream outputStream, HttpRequest request)
        {
            List <Route> routes = this.Routes.Where(x => Regex.Match(request.Url, x.UrlRegex).Success).ToList();

            Dictionary <string, string> headers = new Dictionary <string, string>();

            if (request.Headers.ContainsKey("Origin"))
            {
                //headers.Add("Access-Control-Allow-Origin", request.Headers["Origin"]);
            }

            headers.Add("Connection", "keep-alive");
            headers.Add("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture));
            headers.Add("Server", "distrolucas");

            //headers.Add("Access-Control-Allow-Headers", "authorization, X-PINGOTHER, Content-Type");
            //headers.Add("Access-Control-Max-Age", "86400");
            //headers.Add("Keep-Alive", "timeout=2, max=100");
            //headers.Add("X-DNS-Prefetch-Control", "off");
            //headers.Add("X-Frame-Options", "SAMEORIGIN");
            //headers.Add("Strict-Transport-Security", "max-age=15552000; includeSubDomains");
            //headers.Add("X-Download-Options", "noopen");
            //headers.Add("X-Content-Type-Options", "nosniff");
            //headers.Add("X-XSS-Protection", "1; mode=block");

            if (!routes.Any())
            {
                // check if it's a file
                string pathToFile;
                string host        = request.Headers["Host"];
                string url         = request.Url;
                int    paramsIndex = url.IndexOf('?');
                string urlParams   = "";
                if (paramsIndex != -1)
                {
                    urlParams = url.Remove(0, paramsIndex);
                    url       = url.Remove(paramsIndex, url.Length - paramsIndex);
                }

                if (url.Length == 1)
                {
                    pathToFile = Path.Combine(basePath, indexPath);
                }
                else
                {
                    string actualPath = url.Remove(0, 1);
                    if (actualPath.ToLower().Equals(indexPath.ToLower()))
                    {
                        // index page
                        headers.Add("Location", $"http://{host}");
                        return(new HttpResponse()
                        {
                            ReasonPhrase = "OK",
                            StatusCode = "301",
                            ContentAsUTF8 = "",
                            Headers = headers
                        });
                    }
                    pathToFile = Path.Combine(basePath, actualPath);
                }

                if (Directory.Exists(pathToFile))
                {
                    if (!url.EndsWith("/"))
                    {
                        headers.Add("Location", $"http://{host}/{request.Url.Remove(0, 1)}/");

                        return(new HttpResponse()
                        {
                            ReasonPhrase = "OK",
                            StatusCode = "301",
                            ContentAsUTF8 = "",
                            Headers = headers
                        });
                    }

                    // user input a folder, check if there's an index file
                    string pathToIndex = Path.Combine(pathToFile, indexPath);
                    //headers.Add("Location", $"http://{host}/{request.Url.Remove(0, 1)}/index.html");
                    pathToFile = pathToIndex;
                }

                if (!File.Exists(pathToFile))
                {
                    pathToFile = pathToFile + ".html";
                }

                if (File.Exists(pathToFile))
                {
                    string mime = Path.GetExtension(pathToFile).ToLower();
                    if (mimeTypes.ContainsKey(mime))
                    {
                        headers.Add("Content-Type", mimeTypes[mime]);
                    }
                    else
                    {
                        ConsoleU.WriteLine($"UNKNOWN MIME: {mime}", ConsoleColor.Red);
                    }

                    HttpResponse response = new HttpResponse()
                    {
                        ReasonPhrase = "OK",
                        StatusCode   = "200",
                        Headers      = headers,
                    };
                    response.Content = File.ReadAllBytes(pathToFile);

                    return(response);
                }

                return(new HttpResponse()
                {
                    ReasonPhrase = "NOT FOUND",
                    StatusCode = "404",
                    ContentAsUTF8 = ""
                });
                //return HttpBuilder.NotFound(request.Url, headers);
            }

            //X-DNS-Prefetch-Control →off
            //X-Frame-Options →SAMEORIGIN
            //Strict-Transport-Security →max-age=15552000; includeSubDomains
            //X-Download-Options →noopen
            //X-Content-Type-Options →nosniff
            //X-XSS-Protection →1; mode=block
            //Access-Control-Allow-Origin →*
            //Date →Tue, 16 Jul 2019 19:09:07 GMT
            //Connection →keep-alive
            //Content-Length →0

            if (request.Method == "OPTIONS")
            {
                string allRoutes = "";
                for (int i = 0; i < routes.Count; i++)
                {
                    string r = routes[i].Method;
                    allRoutes += r;
                    if (i != routes.Count - 1)
                    {
                        allRoutes += ", ";
                    }
                }
                headers.Add("Access-Control-Allow-Methods", allRoutes);

                return(new HttpResponse()
                {
                    ReasonPhrase = "",
                    StatusCode = "204",
                    Headers = headers
                });
            }

            Route route = routes.SingleOrDefault(x => x.Method == request.Method);

            if (route == null)
            {
                Console.WriteLine("Method Not Allowed");
                return(new HttpResponse()
                {
                    ReasonPhrase = "Method Not Allowed",
                    StatusCode = "405",
                });
            }

            // extract the path if there is one
            var match = Regex.Match(request.Url, route.UrlRegex);

            if (match.Groups.Count > 1)
            {
                request.Path = match.Groups[1].Value;
            }
            else
            {
                request.Path = request.Url;
            }

            // trigger the route handler...
            request.Route = route;
            try {
                HttpResponse response = route.Callable(request);

                if (response.Headers == null)
                {
                    response.Headers = headers;
                }
                else
                {
                    foreach (var header in headers)
                    {
                        if (!response.Headers.ContainsKey(header.Key))
                        {
                            response.Headers.Add(header.Key, header.Value);
                        }
                    }
                }

                return(response);
            } catch (Exception) {
                //log.Error(ex);
                return(HttpBuilder.InternalServerError(headers));
            }
        }
        Int32 load(String fileName)
        {
            DataTable dtTemp = new DataTable();

            mcontrolItems.Clear();

            String printInfo = "binding control... ...";

            ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning);

            DataSet ds            = new DataSet();
            String  fileExtension = System.IO.Path.GetExtension(fileName);

            if (fileExtension != ".xml" || !System.IO.File.Exists(fileName))
            {
                ConsoleU.writeLine("this file is not xml or path error,please select again!", ConsoleU.Level.Warning);
            }
            ds.ReadXml(fileName);
            dtTemp = ds.Tables[gf_main.DIRCTRL];

            DataSet dsEvent = new DataSet();//load  xml about event DataSet

            dsEvent.ReadXml(fileName);

            if (dtTemp == null)
            {
                printInfo = "Cannot find node,please try again..."; ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning); return(-1);
            }
            if (dtTemp.Rows == null)
            {
                printInfo = "Cannot find node rows,please try again..."; ConsoleU.writeLine(printInfo, ConsoleU.Level.Warning); return(-1);
            }

            foreach (DataRow row in dtTemp.Rows)
            {
                cc_control ctrl = new cc_control();
                try
                { ctrl.Ctr_Text = row[gf_main.CTRLTEXT].ToString(); }
                catch (FormatException) { }
                try
                { ctrl.Ctr_X = Int32.Parse(row[gf_main.CTRLX].ToString()); }
                catch (FormatException) { }
                try
                { ctrl.Ctr_Y = Int32.Parse(row[gf_main.CTRLY].ToString()); }
                catch (FormatException) { }
                try
                { ctrl.Ctr_Width = Int32.Parse(row[gf_main.CTRLWIDTH].ToString()); }
                catch (FormatException) { }
                try
                { ctrl.Ctr_Height = Int32.Parse(row[gf_main.CTRLHEIGHT].ToString()); }
                catch (FormatException) { }
                try
                { ctrl.Ctr_Type = row[gf_main.CTRLTYPE].ToString(); }
                catch (FormatException) { }


                DataRelationCollection childRelations = dtTemp.ChildRelations;//relationship building
                if (childRelations.Count > 0)
                {
                    DataRelation relation = childRelations[String.Format("{0}_{1}", gf_main.DIRCTRL, gf_main.DIREVENT)];
                    DataRow[]    ruleRows = row.GetChildRows(relation);
                    foreach (DataRow ruleRow in ruleRows)
                    {
                        ctrl.mevent.addEvent(ruleRow, dsEvent.Tables[gf_main.DIREVENT]);//init ion controls event
                    }
                }

                mcontrolItems.Add(ctrl);
            }
#if ctrlPrintf
            ConsoleU.writeLine(String.Format("control loaded. . {0}", ctrlCount), ConsoleU.Level.Normal);
#endif
            return(0);
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            // We need this, else Windows will fake
            // all the data about monitors inside the application
            User32Util.SetProcessDpiAwareness(ProcessDPIAwareness.ProcessPerMonitorDPIAware);

            if (args.Length == 0)
            {
                ConsoleU.WriteLine("Invalid usage! Need arguments to proceed!", Palette.Error);
                return;
            }

#if RELEASE
            try
#endif
            {
                for (int i = 0; i < args.Length; i++)
                {
                    string arg = args[i];
                    ConsoleU.WriteLine("Parsing line " + i + ": " + arg, Palette.Feedback);
                    //Log(string.Format("Parsing line {0}: {1}", i, arg));

                    string argument = "";
                    for (int j = i; j < args.Length; j++)
                    {
                        string skey = args[j];
                        if (!skey.Contains("monitors") &&
                            !skey.Contains("game") &&
                            !skey.Contains("partialmutex") &&
                            !skey.Contains("mutextype") &&
                            !skey.Contains("mutex") &&
                            !skey.Contains("proc") &&
                            !skey.Contains("hook") &&
                            !skey.Contains("delay") &&
                            !skey.Contains("renamemutex") &&
                            !skey.Contains("mutextorename") &&
                            !skey.Contains("setwindow") &&
                            !skey.Contains("width") &&
                            !skey.Contains("height") &&
                            !skey.Contains("posx") &&
                            !skey.Contains("posy") &&
                            !skey.Contains("isdebug") &&
                            !skey.Contains("nucleusfolderpath") &&
                            !skey.Contains("blockraw") &&
                            !skey.Contains("nucenv") &&
                            !skey.Contains("playernick") &&
                            !skey.Contains("starthks") &&
                            !skey.Contains("root") &&
                            !skey.Contains("destination") &&
                            !skey.Contains("direxclusions") &&
                            !skey.Contains("fileexclusions") &&
                            !skey.Contains("filecopyinstead") &&
                            !skey.Contains("hardlink") &&
                            !skey.Contains("symfolder") &&
                            !skey.Contains("numplayers") &&
                            !skey.Contains("symlink")
                            //&& !skey.Contains("rawhid")
                            && !skey.Contains("createsingle") &&
                            !skey.Contains("rawhid") &&
                            !skey.Contains("docpath") &&
                            !skey.Contains("usedocs") &&
                            !skey.Contains("output"))


                        {
                            i++;
                            if (string.IsNullOrEmpty(argument))
                            {
                                argument = skey;
                            }
                            else
                            {
                                argument = argument + " " + skey;
                            }
                        }
                    }
                    //Log("Extra arguments:" + argument);
                    ConsoleU.WriteLine("Extra arguments:" + argument, Palette.Feedback);


                    string[] splited = (arg + argument).Split(new string[] { "|::|" }, StringSplitOptions.None);
                    string   key     = splited[0].ToLower();
                    //Log("key " + key);

                    if (key.Contains("monitors"))
                    {
                    }
                    else if (key.Contains("hook"))
                    {
                        isHook = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("delay"))
                    {
                        isDelay = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("renamemutex"))
                    {
                        renameMutex = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("mutextorename"))
                    {
                        mutexToRename = splited[1];
                    }
                    else if (key.Contains("partialmutex"))
                    {
                        partialMutex = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("setwindow"))
                    {
                        setWindow = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("width"))
                    {
                        width = Int32.Parse(splited[1]);
                    }
                    else if (key.Contains("height"))
                    {
                        height = Int32.Parse(splited[1]);
                    }
                    else if (key.Contains("posx"))
                    {
                        posx = Int32.Parse(splited[1]);
                    }
                    else if (key.Contains("posy"))
                    {
                        posy = Int32.Parse(splited[1]);
                    }
                    else if (key.Contains("docpath"))
                    {
                        DocumentsRoot = splited[1];
                    }
                    else if (key.Contains("usedocs"))
                    {
                        useDocs = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("isdebug"))
                    {
                        isDebug = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("nucleusfolderpath"))
                    {
                        nucleusFolderPath = splited[1];
                    }
                    else if (key.Contains("blockraw"))
                    {
                        blockRaw = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("createsingle"))
                    {
                        createSingle = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("rawhid"))
                    {
                        rawHid = splited[1];
                    }
                    else if (key.Contains("nucenv"))
                    {
                        useNucleusEnvironment = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("playernick"))
                    {
                        playerNick = splited[1];
                    }
                    else if (key.Contains("starthks"))
                    {
                        useStartupHooks = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("root"))
                    {
                        root = splited[1];
                    }
                    else if (key.Contains("currentdir"))
                    {
                        currentDir = splited[1];
                    }
                    else if (key.Contains("destination"))
                    {
                        destination = splited[1].Substring(0, splited[1].LastIndexOf('\\'));
                    }
                    else if (key.Contains("direxclusions"))
                    {
                        dirExclusions = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None);
                    }
                    else if (key.Contains("fileexclusions"))
                    {
                        fileExclusions = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None);
                    }
                    else if (key.Contains("filecopyinstead"))
                    {
                        fileCopyInstead = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None);
                    }
                    else if (key.Contains("hardlink"))
                    {
                        hardLink = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("symfolder"))
                    {
                        symFolders = Boolean.Parse(splited[1]);
                    }
                    else if (key.Contains("numplayers"))
                    {
                        numPlayers = int.Parse(splited[1]);
                    }
                    else if (key.Contains("symlink"))
                    {
                        int exitCode = 1;
                        for (int p = 0; p < numPlayers; p++)
                        {
                            Nucleus.Gaming.Platform.Windows.IO.WinDirectoryUtil.LinkDirectory(root, new DirectoryInfo(root), destination + "\\Instance" + p, out exitCode, dirExclusions, fileExclusions, fileCopyInstead, hardLink, symFolders);
                        }
                    }
                    //else if (key.Contains("rawhid"))
                    //{
                    //    rawHid = splited[1];
                    //}
                    else if (key.Contains("game"))
                    {
                        string   data    = splited[1];
                        string[] subArgs = data.Split(';');
                        string   path    = subArgs[0];

                        string argu = null;
                        if (subArgs.Length > 1)
                        {
                            argu = subArgs[1];
                        }

                        string workingDir = null;
                        if (path.Contains("|"))
                        {
                            string[] div = path.Split('|');
                            path       = div[0];
                            workingDir = div[1];
                        }

                        Log($"EXE: {path} ARGS: {argu} WORKDIR: {workingDir}");
                        ConsoleU.WriteLine($"Start game: EXE: {path} ARGS: {argu} WORKDIR: {workingDir}", Palette.Feedback);
                        StartGame(path, argu, workingDir);
                    }
                    else if (key.Contains("mutextype"))
                    {
                        mt = splited[1];
                    }
                    else if (key.Contains("mutex"))
                    {
                        string[] mutex = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None);
                        ConsoleU.WriteLine("Trying to kill mutexes", Palette.Wait);
                        for (int j = 0; j < mutex.Length; j++)
                        {
                            string m = mutex[j];
                            ConsoleU.WriteLine("Trying to kill mutex: " + m, Palette.Feedback);
                            if (!ProcessUtil.KillMutex(proc, mt, m, partialMutex))
                            {
                                ConsoleU.WriteLine("Mutex " + m + " could not be killed", Palette.Error);
                            }
                            else
                            {
                                ConsoleU.WriteLine("Mutex killed " + m, Palette.Success);
                            }
                            Thread.Sleep(150);
                        }
                    }
                    else if (key.Contains("proc"))
                    {
                        string procId = splited[1];
                        int    id     = int.Parse(procId);
                        try
                        {
                            proc = Process.GetProcessById(id);
                            Log(string.Format($"Process ID {id} found!"));
                            ConsoleU.WriteLine($"Process ID {id} found!", Palette.Success);
                        }
                        catch
                        {
                            Log(string.Format($"Process ID {id} not found"));
                            ConsoleU.WriteLine($"Process ID {id} not found", Palette.Error);
                        }
                    }
                    else if (key.Contains("output"))
                    {
                        string[] mutex = splited[1].Split(new string[] { "|==|" }, StringSplitOptions.None);
                        bool     all   = true;

                        for (int j = 0; j < mutex.Length; j++)
                        {
                            string m = mutex[j];
                            ConsoleU.WriteLine("Requested mutex: " + m, Palette.Error);
                            bool exists = ProcessUtil.MutexExists(proc, mt, m, partialMutex);
                            if (!exists)
                            {
                                all = false;
                            }

                            Thread.Sleep(500);
                        }
                        Console.WriteLine(all.ToString());
                    }
                }
            }
#if RELEASE
            catch (Exception ex)
            {
                ConsoleU.WriteLine(ex.Message);
            }
#endif
        }