string Run(string launchPath, params string[] launchArgs)
        {
            var r = string.Empty;

            try
            {
                var pipeOut = new NSPipe();

                var t = new NSTask();
                t.LaunchPath     = launchPath;
                t.Arguments      = launchArgs;
                t.StandardOutput = pipeOut;

                t.Launch();
                //t.WaitUntilExit();
                //t.Release();

                //r = pipeOut.ReadHandle.ReadDataToEndOfFile().ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine("launchctl failed: " + ex);
            }
            return(r);
        }
示例#2
0
        partial void startStopPing(Foundation.NSObject sender)
        {
            if (task != null)
            {
                task.Interrupt();
            }
            else
            {
                task            = new NSTask();
                task.LaunchPath = "/sbin/ping";
                string[] args = { "-c10", hostField.StringValue };

                task.Arguments = args;

                // Create a new pipe
                pipe = new NSPipe();
                task.StandardOutput = pipe;

                NSFileHandle fh = pipe.ReadHandle;

                NSNotificationCenter nc = NSNotificationCenter.DefaultCenter;
                nc.RemoveObserver(this);
                nc.AddObserver(this, new Selector("dataReady:"), NSFileHandle.ReadCompletionNotification, fh);
                nc.AddObserver(this, new Selector("taskTerminated:"), NSTask.NSTaskDidTerminateNotification, task);
                task.Launch();
                outputView.Value = "";

                // Suspect = Obj-C example is [fh readInBackgroundAndNotify] - no arguments
                fh.ReadInBackground();
            }
        }
示例#3
0
partial         void copyFile(Foundation.NSObject sender)
        {
            if (textFieldFrom.StringValue == "" || textFieldTo.StringValue == "") {
                textFieldResults.StringValue = "Must set 'from' and 'to' paths";
                return;
            }

            // Prepare a task object
            NSTask task = new NSTask();
            task.LaunchPath = "/bin/cp";
            string[] args = {textFieldFrom.StringValue, textFieldTo.StringValue};
            task.Arguments = args;

            // Create a pipe to read from
            NSPipe outPipe = new NSPipe();
            task.StandardOutput = outPipe;

            // Start the process
            task.Launch();

            // Read the output
            NSData data = outPipe.ReadHandle.ReadDataToEndOfFile();

            // Make sure the task terminates normally
            task.WaitUntilExit();
            int status = task.TerminationStatus;

            // Check status
            if (status != 0) {
                textFieldResults.StringValue = "Copy Failed: " + status;
                return;
            }

            textFieldResults.StringValue = String.Format("{0} copied to {1}", textFieldFrom.StringValue, textFieldTo.StringValue);
        }
示例#4
0
        public static string Method1()
        {
            string[] args = new string[] { "-rd1", "-c", "IOPlatformExpertDevice", "|", "grep", "model" };
            NSTask   task = new NSTask();

            task.LaunchPath = @"/usr/sbin/ioreg";
            task.Arguments  = args;

            NSPipe pipe = new NSPipe();

            task.StandardOutput = pipe;
            task.Launch();

            string[] args2 = new string[] { "/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }" };

            NSTask task2 = new NSTask();

            task2.LaunchPath = @"/usr/bin/awk";
            task2.Arguments  = args2;

            NSPipe pipe2 = new NSPipe();

            task2.StandardInput  = pipe;
            task2.StandardOutput = pipe2;
            NSFileHandle fileHandle2 = pipe2.ReadHandle;

            task2.Launch();

            NSData   data = fileHandle2.ReadDataToEndOfFile();
            NSString uuid = NSString.FromData(data, NSStringEncoding.UTF8);

            return(uuid.ToString().Replace("\n", ""));
        }
示例#5
0
        public override void FinishedLaunching(MonoMac.Foundation.NSObject notification)
        {
            Directory.SetCurrentDirectory(NSBundle.MainBundle.ResourcePath);

            if (getMaxfiles() < 512)
            {
                runCommand("launchctl", "limit maxfiles 512 4096");

                string execPath  = NSBundle.MainBundle.BundlePath;
                int    processId = NSProcessInfo.ProcessInfo.ProcessIdentifier;
                NSTask.LaunchFromPath("relaunch", new string[] { execPath, processId.ToString() });

                Environment.Exit(0);
            }

            WebClient updateClient = new WebClient();

            updateClient.DownloadStringCompleted += UpdateCheckCompleted;
            updateClient.DownloadStringAsync(new Uri("http://dl.dropbox.com/u/76985/MacTerraria_update.txt"));

            patchTerraria(Path.Combine(NSBundle.MainBundle.ResourcePath, "exes", "Terraria.exe"),
                          Path.Combine(NSBundle.MainBundle.ResourcePath, "Terraria.exe"));

            string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games", "Terraria");

            Directory.CreateDirectory(savePath);



            Assembly assembly = Assembly.LoadFrom(Path.Combine(NSBundle.MainBundle.ResourcePath, "Terraria.exe"));
            Type     mainType = assembly.GetType("Terraria.Main");
            object   game     = Activator.CreateInstance(mainType);

            mainType.InvokeMember("Run", BindingFlags.Default | BindingFlags.InvokeMethod, null, game, null);
        }
示例#6
0
        public static NSObject NotifyTerminated(
            this NSTask task,
            NSNotificationCenter notificationCenter,
            Action <NSTask> handler)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            NSObject observer = null;

            observer = notificationCenter.AddObserver(
                NSTask.NSTaskDidTerminateNotification,
                notification => {
                if (notification.Object == task)
                {
                    notificationCenter.RemoveObserver(observer);
                    handler(task);
                }
            });

            return(observer);
        }
示例#7
0
        public void OpenTerminal(AbsoluteDirectoryPath containingDirectory)
        {
            var t = new NSTask();

            t.LaunchPath = "/usr/bin/osascript";
            t.Arguments  = new [] { "-e", "tell application \"Terminal\"\ndo script \"cd \\\"" + containingDirectory.NativePath + "\\\"\"\nactivate\nend tell" };
            t.Launch();
        }
示例#8
0
        public ActionResult DeleteConfirmed(int id)
        {
            NSTask nSTask = db.NSTasks.Find(id);

            db.NSTasks.Remove(nSTask);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#9
0
 public ActionResult Edit([Bind(Include = "NSTaskID,Name,Hours,AssignedTo,TaskType")] NSTask nSTask)
 {
     if (ModelState.IsValid)
     {
         db.Entry(nSTask).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(nSTask));
 }
示例#10
0
        public static void Relaunch(this NSApplication self)
        {
            var pid    = NSProcessInfo.ProcessInfo.ProcessIdentifier;
            var script = string.Format(@"
                while [ `ps -p {0} | wc -l` -gt 1 ]; do sleep 0.1; done; open '{1}'
            ", pid, NSBundle.MainBundle.BundlePath);

            NSTask.LaunchFromPath("/bin/sh", new [] { "-c", script });
            self.Terminate(self);
        }
示例#11
0
        public ActionResult Create([Bind(Include = "NSTaskID,Name,Hours,AssignedTo,TaskType")] NSTask nSTask)
        {
            if (ModelState.IsValid)
            {
                db.NSTasks.Add(nSTask);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(nSTask));
        }
示例#12
0
        static void restart_WillTerminate(object sender, EventArgs e)
        {
            // re-open after we terminate
            var args = new string[] {
                "-c",
                "open \"$1\"",
                string.Empty,
                NSBundle.MainBundle.BundlePath
            };

            NSTask.LaunchFromPath("/bin/sh", args);
        }
示例#13
0
        // GET: NSTasks/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            NSTask nSTask = db.NSTasks.Find(id);

            if (nSTask == null)
            {
                return(HttpNotFound());
            }
            return(View(nSTask));
        }
示例#14
0
        private async void ResetBtnClicked(object sender, EventArgs e)
        {
            var arg = (sender.GetType() == typeof(Frame)) ? "archive" : String.Empty;

#if WINDOWS_UWP
            if (arg == String.Empty)
            {
                await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Clean");

                await CoreApplication.RequestRestartAsync("Application Restart Programmatically ");
            }
            else
            {
                await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Archive");

                await Navigation.PushAsync(new RestartPage());

                var pref = ViewModePreferences.CreateDefault(ApplicationViewMode.CompactOverlay);
                pref.CustomSize = new Windows.Foundation.Size(400, 600);

                await ApplicationView.GetForCurrentView().TryEnterViewModeAsync(ApplicationViewMode.CompactOverlay, pref);
            }
#elif __MACOS__
            if (arg == String.Empty)
            {
                var process = new ProcessStartInfo("scripts/cleanup.sh", arg);
                Process.Start(process).WaitForExit();

                var path = NSBundle.MainBundle.BundlePath;
                var task = new NSTask
                {
                    LaunchPath = "/usr/bin/open",
                    Arguments  = new string[] { path }
                };
                task.Launch();
                Environment.Exit(0);
            }
            else
            {
                var process = new ProcessStartInfo("scripts/cleanup.sh", arg);
                Process.Start(process);

                NSApplication.SharedApplication.MainWindow.ToggleFullScreen(NSApplication.SharedApplication.MainWindow);
                NSApplication.SharedApplication.MainWindow.Level = NSWindowLevel.Floating;
                await Navigation.PushAsync(new RestartPage());
            }
#endif
        }
示例#15
0
        public static NSTask LaunchTaskForPath(string path, string[] args, bool activate = true)
        {
            var task = new NSTask();
            var pipe = new NSPipe();

            task.StandardOutput = pipe;
            task.LaunchPath     = path;
            task.Arguments      = args;
            task.Launch();

            if (activate)
            {
                NSApplicationEx.Activate(task.ProcessIdentifier);
            }

            return(task);
        }
        //https://forums.xamarin.com/discussion/comment/178452#Comment_178452


        public void RunConsoleParameters(string[] consoleParams, string pathToApp)
        {
            //string[] args = new string[] { "-p", " sp" };
            string[] args = consoleParams;

            NSTask task = new NSTask();

            //path to app
            //task.LaunchPath = "/Applications/MyApp.app/Contents/MacOS/MyApp";
            task.LaunchPath = pathToApp;

            task.Arguments = args;

            NSPipe pipe = new NSPipe();

            task.StandardOutput = pipe;
            task.Launch();
        }
示例#17
0
        private async void ResetClicked(object sender, EventArgs e)
        {
#if WINDOWS_UWP
            await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Reset");

            await CoreApplication.RequestRestartAsync("Application Restart Programmatically ");
#elif __MACOS__
            var process = new ProcessStartInfo("scripts/cleanup.sh", "reset");
            Process.Start(process).WaitForExit();

            var path = NSBundle.MainBundle.BundlePath;
            var task = new NSTask
            {
                LaunchPath = "/usr/bin/open",
                Arguments  = new string[] { path }
            };
            task.Launch();
            Environment.Exit(0);
#endif
        }
示例#18
0
        public override void ShellSyncCore(string path, string[] arguments, string autoWriteStdin, out string stdout, out string stderr, out int exitCode)
        {
            if (autoWriteStdin != "")
            {
                throw new Exception("ShellSyncCore::AutoWriteStdin not supported in macOS");                 // Never need yet, used only in Linux
            }
            try
            {
                var pipeOut = new NSPipe();
                var pipeErr = new NSPipe();

                var t = new NSTask();

                t.LaunchPath     = path;
                t.Arguments      = arguments;
                t.StandardOutput = pipeOut;
                t.StandardError  = pipeErr;

                t.Launch();
                t.WaitUntilExit();
                //t.Release();
                t.Dispose();

                NSFileHandle fileOut = pipeOut.ReadHandle;
                stdout = fileOut.ReadDataToEndOfFile().ToString();
                fileOut.CloseFile();

                NSFileHandle fileErr = pipeErr.ReadHandle;
                stderr = fileErr.ReadDataToEndOfFile().ToString();
                fileErr.CloseFile();

                exitCode = t.TerminationStatus;
            }
            catch (Exception ex)
            {
                stdout   = "";
                stderr   = "Error: " + ex.Message;
                exitCode = -1;
            }
        }
示例#19
0
        partial void moveFile(Foundation.NSObject sender)
        {
            if (textFieldFrom.StringValue == "" || textFieldTo.StringValue == "")
            {
                textFieldResults.StringValue = "Must set 'from' and 'to' paths";
                return;
            }

            // Prepare a task object
            NSTask task = new NSTask();

            task.LaunchPath = "/bin/mv";
            string[] args = { textFieldFrom.StringValue, textFieldTo.StringValue };
            task.Arguments = args;

            // Create a pipe to read from
            NSPipe outPipe = new NSPipe();

            task.StandardOutput = outPipe;

            // Start the process
            task.Launch();

            // Read the output
            NSData data = outPipe.ReadHandle.ReadDataToEndOfFile();

            // Make sure the task terminates normally
            task.WaitUntilExit();
            int status = task.TerminationStatus;

            // Check status
            if (status != 0)
            {
                textFieldResults.StringValue = "Move Failed: " + status;
                return;
            }

            textFieldResults.StringValue = String.Format("{0} moved to {1}", textFieldFrom.StringValue, textFieldTo.StringValue);
        }
示例#20
0
        public static string RunTask(string task, params string[] args)
        {
            var r = string.Empty;

            try
            {
                var pipeOut = new NSPipe();

                var t = new NSTask();
                t.LaunchPath = task;
                if (args != null)
                {
                    t.Arguments = args;
                }

                var path = "/usr/local/bin";
                var env  = new NSMutableDictionary();
                env.SetValueForKey(new NSString(path), new NSString("PATH"));

                t.Environment = env;

                t.StandardOutput = pipeOut;
                t.StandardError  = pipeOut;

                t.Launch();
                t.WaitUntilExit();
                //t.Release ();

                r = pipeOut.ReadHandle.ReadDataToEndOfFile().ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(task + " failed: " + ex);
            }
            return(r);
        }
示例#21
0
        public override void ShellSync(string path, string[] arguments, out string stdout, out string stderr, out int exitCode)
        {
            try
            {
                var pipeOut = new NSPipe();
                var pipeErr = new NSPipe();

                var t = new NSTask();

                t.LaunchPath     = path;
                t.Arguments      = arguments;
                t.StandardOutput = pipeOut;
                t.StandardError  = pipeErr;

                t.Launch();
                t.WaitUntilExit();
                //t.Release();
                t.Dispose();

                NSFileHandle fileOut = pipeOut.ReadHandle;
                stdout = fileOut.ReadDataToEndOfFile().ToString();
                fileOut.CloseFile();

                NSFileHandle fileErr = pipeErr.ReadHandle;
                stderr = fileErr.ReadDataToEndOfFile().ToString();
                fileErr.CloseFile();

                exitCode = t.TerminationStatus;
            }
            catch (Exception ex)
            {
                stdout   = "";
                stderr   = "Error: " + ex.Message;
                exitCode = -1;
            }
        }
示例#22
0
        public override bool ReadFromUrl(NSUrl url, string typeName, out NSError outError)
        {
            outError = null;
            // Which files are we getting the zipinfo for?
            string filename = url.Path;

            string lPath = "";
            string flags = "";
            Console.WriteLine("Type Name: {0}", typeName);
            switch (typeName)
            {
                case "public.zip-archive":
                    lPath = "/usr/bin/zipinfo";
                    flags = "-1";
                    break;
                case "public.tar-archive":
                    lPath = "/usr/bin/tar";
                    flags = "tf";
                    break;
                case "org.gnu.gnu-zip-tar-archive":
                    lPath = "/usr/bin/tar";
                    flags = "tzf";
                    break;
                default:
                    NSDictionary eDict = NSDictionary.FromObjectAndKey(new NSString("Archive type not supported"), NSError.LocalizedFailureReasonErrorKey);
                    outError = NSError.FromDomain(NSError.OsStatusErrorDomain,0, eDict);
                    break;
            }

            // Prepare a task object
            NSTask task = new NSTask();
            task.LaunchPath = lPath;
            string[] args = {flags, filename};
            task.Arguments = args;

            // Create a pipe to read from
            NSPipe outPipe = new NSPipe();
            task.StandardOutput = outPipe;

            // Start the process
            task.Launch();

            // Read the output
            NSData data = outPipe.ReadHandle.ReadDataToEndOfFile();

            // Make sure the task terminates normally
            task.WaitUntilExit();
            int status = task.TerminationStatus;

            // Check status
            if (status != 0) {
                if (outError != null) {
                    NSDictionary eDict = NSDictionary.FromObjectAndKey(new NSString("zipinfo failed"), NSError.LocalizedFailureReasonErrorKey);
                    outError = NSError.FromDomain(NSError.OsStatusErrorDomain,0, eDict);
                }
                return false;
            }

            // Convert to a string
            string aString = NSString.FromData(data,NSStringEncoding.UTF8).ToString();

            // Break the string into lines
            MyDocument.filenames = aString.Split(new char[]{'\n'});
            Console.WriteLine(MyDocument.filenames);

            // In case of revert
            //			tableView.ReloadData();

            return true;
        }
示例#23
0
        public void Write(Action <NSFileHandle> writeHandler)
        {
            if (writeHandler == null)
            {
                throw new ArgumentNullException(nameof(writeHandler));
            }

            var args = new List <string> {
                "-extauth"
            };

            if (Create)
            {
                args.Add("-c");
            }

            if (Mode > 0)
            {
                args.Add("-m");
                args.Add("0" + Convert.ToString(Mode, 8));
            }

            args.Add("-w");
            args.Add(Path);

            var task = new NSTask {
                LaunchPath = "/usr/libexec/authopen",
                Arguments  = args.ToArray()
            };

            var stdinPipe  = new NSPipe();
            var stderrPipe = new NSPipe();

            task.StandardInput = stdinPipe;
            task.StandardError = stderrPipe;

            try {
                task.Launch();

                stdinPipe.WriteHandle.WriteData(Authorization.MakeExternalForm());
                writeHandler(stdinPipe.WriteHandle);
            } finally {
                stdinPipe.WriteHandle.CloseFile();
            }

            task.WaitUntilExit();

            try {
                if (task.TerminationReason == NSTaskTerminationReason.Exit &&
                    task.TerminationStatus == 0)
                {
                    return;
                }

                var errorMessage = stderrPipe
                                   .ReadHandle
                                   .ReadDataToEndOfFile()
                                   .ToString()
                                   .Trim();

                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage =
                        $"authopen failed with termination reason {task.TerminationReason} " +
                        $"and termination status {task.TerminationStatus}";
                }

                throw new Exception(errorMessage);
            } finally {
                stderrPipe.ReadHandle.CloseFile();
            }
        }
示例#24
0
        public static Process[] GetProcesses()
        {
            // spin up the objective-c runtime
            ObjectiveCRuntime.LoadFramework("Cocoa");
            ObjectiveCRuntime.Initialize();
            NSAutoreleasePool pool = new NSAutoreleasePool();

            // Create our process
            NSTask getPSTask        = new NSTask();
            NSPipe getPSStandardOut = new NSPipe();

            getPSTask.StandardOutput = getPSStandardOut;
            getPSTask.LaunchPath     = @"/bin/ps";

            // add some arguments
            NSString getPSargumentString = new NSString("-ax");
            NSArray  getPSarguments      = NSArray.ArrayWithObject(getPSargumentString);

            getPSTask.Arguments = getPSarguments;

            // We have liftoff
            getPSTask.Launch();
            getPSTask.WaitUntilExit();

            // Parse the output
            NSData   getPSoutput    = getPSStandardOut.FileHandleForReading.ReadDataToEndOfFile;
            NSString getPSoutString = new NSString(getPSoutput, NSStringEncoding.NSUTF8StringEncoding);


            // Split the string of output in to a list of processes
            string[] getPSsplitString = getPSoutString.ToString().Split(Environment.NewLine.ToCharArray());

            // Remove the first and last line of the output
            string[] processListAsStrings = new string[getPSsplitString.Length - 2];
            for (int x = 1; x < getPSsplitString.Length - 1; x++)
            {
                processListAsStrings[x - 1] = getPSsplitString[x];
            }


            Process[] processes = new Process[processListAsStrings.Length];


            for (int i = 0; i < processes.Length; i++)
            {
                string cleanString = RemoveExtraSpaces(processListAsStrings[i]);

                string[] processDetails = cleanString.Split(' ');
                Int32    procID         = Convert.ToInt32(processDetails[0]);

                string procName = string.Empty;
                for (int j = 4; j < processDetails.Length; j++)
                {
                    if (j == 4)
                    {
                        procName = procName + processDetails[j];
                    }
                    else
                    {
                        procName = procName + " " + processDetails[j];
                    }
                }

                //Console.WriteLine(procID.ToString() + procName);
                processes[i] = new Process(procID, procName);
            }

            // Dipose our Objective-C objects, gotta love reference counting
            pool.Release();

            return(processes);
        }
示例#25
0
 void TaskTerminated(NSNotification n)
 {
     Console.WriteLine("Task Terminated");
     task = null;
     startButton.State = NSCellStateValue.Off;
 }
示例#26
0
文件: clsRAR.cs 项目: luicil/MacRAR
        public string OpenRAR(string path, MainWindow  window, NSTableView TableView)
        {
            if (path.Length > 0) {
                clsIOPrefs ioPrefs = new clsIOPrefs ();
                string txtRAR = ioPrefs.GetStringValue ("CaminhoRAR");
                if (txtRAR.Length > 0) {
                    string[] launchArgs = {"vt",  path};
                    NSPipe pipeOut = new NSPipe();
                    NSTask t =  new NSTask();
                    t.LaunchPath = txtRAR;
                    t.Arguments = launchArgs;
                    t.StandardOutput = pipeOut;
                    t.Launch ();
                    ViewArquivosDataSource datasource = new ViewArquivosDataSource ();

                    ProgressWindowController sheet = null;
                    TableView.InvokeOnMainThread (delegate {
                        sheet = new ProgressWindowController  ();
                        sheet.ShowSheet (window);
                    });

                    bool Cancela = false;

                    do {
                        string txtRET = pipeOut.ReadHandle.ReadDataToEndOfFile ().ToString ();
                        int pos = txtRET.IndexOf ("Name:");
                        if (pos > 0) {
                            TableView.InvokeOnMainThread(delegate{
                                if(!TableView.Enabled) {
                                    TableView.Enabled = true;
                                    TableView.Hidden = false;
                                    window.tb_outAdicionarActive = true;
                                    window.tb_outAtualizarActive = true;
                                    window.tb_outExtrairActive = true;
                                    window.tb_outRemoverActive = true;
                                    window.tb_outDesfazerActive = true;
                                }
                            });

                            txtRET = txtRET.Substring (pos);
                            List<string> nomes = new List<string>();
                            do {
                                pos = txtRET.IndexOf ("Name:",pos + 1);
                                if (pos < 0) {
                                    nomes.Add (txtRET.Trim());
                                    break;
                                }
                                nomes.Add(txtRET.Substring(0, pos - 2).Trim());
                                txtRET = txtRET.Substring(pos);
                                pos = 0;
                            } while (true);
                            if (nomes.Count > 0) {

                                sheet.InvokeOnMainThread(delegate{
                                    sheet.ProgressBarMinValue = 0;
                                    sheet.ProgressBarMaxValue = nomes.Count;
                                });

                                double conta = 0;

                                foreach (string nome in nomes) {

                                    clsViewArquivos viewArquivos = new clsViewArquivos ();
                                    string[] colunas = nome.Split ('\n');
                                    string tipo = colunas [1].Substring (colunas [1].IndexOf (":") + 1).Trim();
                                    viewArquivos.Nome = colunas [0].Substring (colunas [0].IndexOf (":") + 1).Trim();
                                    viewArquivos.Tipo = colunas [1].Substring (colunas [1].IndexOf (":") + 1).Trim();

                                    ++conta;

                                    sheet.InvokeOnMainThread(delegate{
                                        sheet.LabelArqValue = "Processando arquivo: " + viewArquivos.Nome;
                                        sheet.ProgressBarValue = conta;
                                    });

            //									NSApplication.SharedApplication.InvokeOnMainThread (() => {
            //										sheet.LabelArqValue = "Processando arquivo: " + viewArquivos.Nome;
            //										sheet.ProgressBarValue = conta;
            //									});

                                    if (tipo == "File") {
                                        viewArquivos.Tamanho = colunas [2].Substring (colunas [2].IndexOf (":") + 1).Trim();
                                        viewArquivos.Compactado = colunas [3].Substring (colunas [3].IndexOf (":") + 1).Trim();
                                        viewArquivos.Compressao = colunas [4].Substring (colunas [4].IndexOf (":") + 1).Trim();
                                        viewArquivos.DataHora = colunas [5].Substring (colunas [5].IndexOf (":") + 1).Trim();
                                        viewArquivos.Atributos = colunas [6].Substring (colunas [6].IndexOf (":") + 1).Trim();
                                        viewArquivos.CRC32 = colunas [7].Substring (colunas [7].IndexOf (":") + 1).Trim();
                                        viewArquivos.OS = colunas [8].Substring (colunas [8].IndexOf (":") + 1).Trim();
                                        viewArquivos.Compressor = colunas [9].Substring (colunas [9].IndexOf (":") + 1).Trim();
                                    } else {
                                        viewArquivos.Tamanho = "";
                                        viewArquivos.Compactado = "";
                                        viewArquivos.Compressao = "";
                                        viewArquivos.DataHora = colunas [2].Substring (colunas [2].IndexOf (":") + 1).Trim();
                                        viewArquivos.Atributos = colunas [3].Substring (colunas [3].IndexOf (":") + 1).Trim();
                                        viewArquivos.CRC32 = colunas [4].Substring (colunas [4].IndexOf (":") + 1).Trim();
                                        viewArquivos.OS = colunas [5].Substring (colunas [5].IndexOf (":") + 1).Trim();
                                        viewArquivos.Compressor = colunas [6].Substring (colunas [6].IndexOf (":") + 1).Trim();
                                    }
                                    viewArquivos.Tags = "0";
                                    datasource.ViewArquivos.Add (viewArquivos);
                                    viewArquivos = null;

                                    sheet.InvokeOnMainThread(delegate{
                                        Cancela = sheet.Canceled;
                                    });
                                    if(Cancela) {
                                        break;
                                    }
                                }
                            }
                        } else {

                            TableView.InvokeOnMainThread (delegate {
                                TableView.Enabled = false;
                                TableView.Hidden = true;
                                sheet.CloseSheet();
                                NSAlert alert = new NSAlert () {
                                    AlertStyle = NSAlertStyle.Critical,
                                    InformativeText = "Não foi possível processar o arquivo:\r\n" + path,
                                    MessageText = "Abrir Arquivo",
                                };
                                alert.RunSheetModal(window);
                            });

                        }

                        if(Cancela) {
                            break;
                        }

                    } while(t.IsRunning);

                    sheet.InvokeOnMainThread (delegate {
                        sheet.CloseSheet ();
                        sheet = null;
                    });

                    pipeOut.Dispose ();
                    pipeOut = null;

                    TableView.InvokeOnMainThread (delegate {
                        TableView.DataSource = datasource;
                        TableView.Delegate = new ViewArquivosDelegate (datasource);
                    });

                    t.Terminate ();
                    t.Dispose ();
                    t = null;
                }
                ioPrefs = null;
            }
            return path;
        }
示例#27
0
        public override bool ReadFromUrl(NSUrl url, string typeName, out NSError outError)
        {
            outError = null;
            // Which files are we getting the zipinfo for?
            string filename = url.Path;


            string lPath = "";
            string flags = "";

            Console.WriteLine("Type Name: {0}", typeName);
            switch (typeName)
            {
            case "public.zip-archive":
                lPath = "/usr/bin/zipinfo";
                flags = "-1";
                break;

            case "public.tar-archive":
                lPath = "/usr/bin/tar";
                flags = "tf";
                break;

            case "org.gnu.gnu-zip-tar-archive":
                lPath = "/usr/bin/tar";
                flags = "tzf";
                break;

            default:
                NSDictionary eDict = NSDictionary.FromObjectAndKey(new NSString("Archive type not supported"), NSError.LocalizedFailureReasonErrorKey);
                outError = NSError.FromDomain(NSError.OsStatusErrorDomain, 0, eDict);
                break;
            }

            // Prepare a task object
            NSTask task = new NSTask();

            task.LaunchPath = lPath;
            string[] args = { flags, filename };
            task.Arguments = args;

            // Create a pipe to read from
            NSPipe outPipe = new NSPipe();

            task.StandardOutput = outPipe;

            // Start the process
            task.Launch();

            // Read the output
            NSData data = outPipe.ReadHandle.ReadDataToEndOfFile();

            // Make sure the task terminates normally
            task.WaitUntilExit();
            int status = task.TerminationStatus;

            // Check status
            if (status != 0)
            {
                if (outError != null)
                {
                    NSDictionary eDict = NSDictionary.FromObjectAndKey(new NSString("zipinfo failed"), NSError.LocalizedFailureReasonErrorKey);
                    outError = NSError.FromDomain(NSError.OsStatusErrorDomain, 0, eDict);
                }
                return(false);
            }

            // Convert to a string
            string aString = NSString.FromData(data, NSStringEncoding.UTF8).ToString();

            // Break the string into lines
            MyDocument.filenames = aString.Split(new char[] { '\n' });
            Console.WriteLine(MyDocument.filenames);

            // In case of revert
//			tableView.ReloadData();

            return(true);
        }
示例#28
0
 void TaskTerminated(NSNotification n)
 {
     Console.WriteLine("Task Terminated");
     task = null;
     startButton.State = NSCellStateValue.Off;
 }
示例#29
0
partial         void startStopPing(Foundation.NSObject sender)
        {
            if (task != null) {
                task.Interrupt();
            }
            else {
                task = new NSTask();
                task.LaunchPath = "/sbin/ping";
                string[] args = {"-c10", hostField.StringValue};

                task.Arguments = args;

                // Create a new pipe
                pipe = new NSPipe();
                task.StandardOutput = pipe;

                NSFileHandle fh = pipe.ReadHandle;

                NSNotificationCenter nc = NSNotificationCenter.DefaultCenter;
                nc.RemoveObserver(this);
                nc.AddObserver(this, new Selector("dataReady:"), NSFileHandle.ReadCompletionNotification, fh);
                nc.AddObserver(this, new Selector("taskTerminated:"), NSTask.NSTaskDidTerminateNotification, task);
                task.Launch();
                outputView.Value = "";

                // Suspect = Obj-C example is [fh readInBackgroundAndNotify] - no arguments
                fh.ReadInBackground();
            }
        }
示例#30
0
文件: clsRAR.cs 项目: luicil/MacRAR
        public string OpenRAR(string path, MainWindow window, NSTableView TableView)
        {
            if (path.Length > 0)
            {
                clsIOPrefs ioPrefs = new clsIOPrefs();
                string     txtRAR  = ioPrefs.GetStringValue("CaminhoRAR");
                if (txtRAR.Length > 0)
                {
                    string[] launchArgs = { "vt", path };
                    NSPipe   pipeOut    = new NSPipe();
                    NSTask   t          = new NSTask();
                    t.LaunchPath     = txtRAR;
                    t.Arguments      = launchArgs;
                    t.StandardOutput = pipeOut;
                    t.Launch();
                    ViewArquivosDataSource datasource = new ViewArquivosDataSource();

                    ProgressWindowController sheet = null;
                    TableView.InvokeOnMainThread(delegate {
                        sheet = new ProgressWindowController();
                        sheet.ShowSheet(window);
                    });

                    bool Cancela = false;

                    do
                    {
                        string txtRET = pipeOut.ReadHandle.ReadDataToEndOfFile().ToString();
                        int    pos    = txtRET.IndexOf("Name:");
                        if (pos > 0)
                        {
                            TableView.InvokeOnMainThread(delegate {
                                if (!TableView.Enabled)
                                {
                                    TableView.Enabled            = true;
                                    TableView.Hidden             = false;
                                    window.tb_outAdicionarActive = true;
                                    window.tb_outAtualizarActive = true;
                                    window.tb_outExtrairActive   = true;
                                    window.tb_outRemoverActive   = true;
                                    window.tb_outDesfazerActive  = true;
                                }
                            });

                            txtRET = txtRET.Substring(pos);
                            List <string> nomes = new List <string>();
                            do
                            {
                                pos = txtRET.IndexOf("Name:", pos + 1);
                                if (pos < 0)
                                {
                                    nomes.Add(txtRET.Trim());
                                    break;
                                }
                                nomes.Add(txtRET.Substring(0, pos - 2).Trim());
                                txtRET = txtRET.Substring(pos);
                                pos    = 0;
                            } while (true);
                            if (nomes.Count > 0)
                            {
                                sheet.InvokeOnMainThread(delegate {
                                    sheet.ProgressBarMinValue = 0;
                                    sheet.ProgressBarMaxValue = nomes.Count;
                                });

                                double conta = 0;

                                foreach (string nome in nomes)
                                {
                                    clsViewArquivos viewArquivos = new clsViewArquivos();
                                    string[]        colunas      = nome.Split('\n');
                                    string          tipo         = colunas [1].Substring(colunas [1].IndexOf(":") + 1).Trim();
                                    viewArquivos.Nome = colunas [0].Substring(colunas [0].IndexOf(":") + 1).Trim();
                                    viewArquivos.Tipo = colunas [1].Substring(colunas [1].IndexOf(":") + 1).Trim();

                                    ++conta;

                                    sheet.InvokeOnMainThread(delegate {
                                        sheet.LabelArqValue    = "Processando arquivo: " + viewArquivos.Nome;
                                        sheet.ProgressBarValue = conta;
                                    });

//									NSApplication.SharedApplication.InvokeOnMainThread (() => {
//										sheet.LabelArqValue = "Processando arquivo: " + viewArquivos.Nome;
//										sheet.ProgressBarValue = conta;
//									});

                                    if (tipo == "File")
                                    {
                                        viewArquivos.Tamanho    = colunas [2].Substring(colunas [2].IndexOf(":") + 1).Trim();
                                        viewArquivos.Compactado = colunas [3].Substring(colunas [3].IndexOf(":") + 1).Trim();
                                        viewArquivos.Compressao = colunas [4].Substring(colunas [4].IndexOf(":") + 1).Trim();
                                        viewArquivos.DataHora   = colunas [5].Substring(colunas [5].IndexOf(":") + 1).Trim();
                                        viewArquivos.Atributos  = colunas [6].Substring(colunas [6].IndexOf(":") + 1).Trim();
                                        viewArquivos.CRC32      = colunas [7].Substring(colunas [7].IndexOf(":") + 1).Trim();
                                        viewArquivos.OS         = colunas [8].Substring(colunas [8].IndexOf(":") + 1).Trim();
                                        viewArquivos.Compressor = colunas [9].Substring(colunas [9].IndexOf(":") + 1).Trim();
                                    }
                                    else
                                    {
                                        viewArquivos.Tamanho    = "";
                                        viewArquivos.Compactado = "";
                                        viewArquivos.Compressao = "";
                                        viewArquivos.DataHora   = colunas [2].Substring(colunas [2].IndexOf(":") + 1).Trim();
                                        viewArquivos.Atributos  = colunas [3].Substring(colunas [3].IndexOf(":") + 1).Trim();
                                        viewArquivos.CRC32      = colunas [4].Substring(colunas [4].IndexOf(":") + 1).Trim();
                                        viewArquivos.OS         = colunas [5].Substring(colunas [5].IndexOf(":") + 1).Trim();
                                        viewArquivos.Compressor = colunas [6].Substring(colunas [6].IndexOf(":") + 1).Trim();
                                    }
                                    viewArquivos.Tags = "0";
                                    datasource.ViewArquivos.Add(viewArquivos);
                                    viewArquivos = null;

                                    sheet.InvokeOnMainThread(delegate {
                                        Cancela = sheet.Canceled;
                                    });
                                    if (Cancela)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            TableView.InvokeOnMainThread(delegate {
                                TableView.Enabled = false;
                                TableView.Hidden  = true;
                                sheet.CloseSheet();
                                NSAlert alert = new NSAlert()
                                {
                                    AlertStyle      = NSAlertStyle.Critical,
                                    InformativeText = "Não foi possível processar o arquivo:\r\n" + path,
                                    MessageText     = "Abrir Arquivo",
                                };
                                alert.RunSheetModal(window);
                            });
                        }

                        if (Cancela)
                        {
                            break;
                        }
                    } while(t.IsRunning);

                    sheet.InvokeOnMainThread(delegate {
                        sheet.CloseSheet();
                        sheet = null;
                    });

                    pipeOut.Dispose();
                    pipeOut = null;

                    TableView.InvokeOnMainThread(delegate {
                        TableView.DataSource = datasource;
                        TableView.Delegate   = new ViewArquivosDelegate(datasource);
                    });

                    t.Terminate();
                    t.Dispose();
                    t = null;
                }
                ioPrefs = null;
            }
            return(path);
        }
示例#31
0
文件: clsRAR.cs 项目: luicil/MacRAR
        public void ExtractRAR(MainWindow  window, NSTableView TableView, NSIndexSet nSelRows, string rarFile, string extractPath)
        {
            clsIOPrefs ioPrefs = new clsIOPrefs ();
            string txtRAR = ioPrefs.GetStringValue ("CaminhoRAR");
            if (txtRAR.Length > 0) {

                if (nSelRows.Count > 0) {

                    ProgressWindowController sheet = null;
                    TableView.InvokeOnMainThread (delegate {
                        sheet = new ProgressWindowController  ();
                        sheet.ShowSheet (window);
                    });

                    sheet.InvokeOnMainThread(delegate{
                        sheet.ProgressBarMinValue = 0;
                        sheet.ProgressBarMaxValue = nSelRows.Count;
                    });

                    double conta = 0;
                    bool Cancela = false;

                    nuint[] nRows = nSelRows.ToArray ();

                    ViewArquivosDataSource datasource = null;
                    TableView.InvokeOnMainThread(delegate
                        {
                            datasource = (ViewArquivosDataSource)TableView.DataSource;
                        });

                    foreach (int lRow in nRows) {
                        string NomeArq = datasource.ViewArquivos [lRow].Nome;

                        ++conta;

                        sheet.InvokeOnMainThread(delegate{
                            sheet.LabelArqValue = "Extraindo arquivo: " + NomeArq;
                            sheet.ProgressBarValue = conta;
                        });

                        string[] launchArgs = { "x", rarFile, NomeArq, extractPath };
                        NSPipe pipeOut = new NSPipe ();
                        NSTask t = new NSTask ();
                        t.LaunchPath = txtRAR;
                        t.Arguments = launchArgs;
                        t.StandardOutput = pipeOut;
                        t.Launch ();
                        t.WaitUntilExit();

                        //string txtRET = pipeOut.ReadHandle.ReadDataToEndOfFile ().ToString ();

                        sheet.InvokeOnMainThread(delegate{
                            Cancela = sheet.Canceled;
                        });
                        if(Cancela) {
                            break;
                        }

                    }

                    sheet.InvokeOnMainThread (delegate {
                        sheet.CloseSheet ();
                        sheet = null;
                    });

                    if (!Cancela)
                    {
                        TableView.InvokeOnMainThread (delegate {
                            NSAlert alert = new NSAlert () {
                                AlertStyle = NSAlertStyle.Informational,
                                InformativeText = "Arquivo(s) extraido(s) com sucesso !",
                                MessageText = "Extrair arquivos",
                            };
                            alert.RunSheetModal(window);
                        });

                    }

                }
            }
        }
示例#32
0
文件: clsRAR.cs 项目: luicil/MacRAR
        public void ExtractRAR(MainWindow window, NSTableView TableView, NSIndexSet nSelRows, string rarFile, string extractPath)
        {
            clsIOPrefs ioPrefs = new clsIOPrefs();
            string     txtRAR  = ioPrefs.GetStringValue("CaminhoRAR");

            if (txtRAR.Length > 0)
            {
                if (nSelRows.Count > 0)
                {
                    ProgressWindowController sheet = null;
                    TableView.InvokeOnMainThread(delegate {
                        sheet = new ProgressWindowController();
                        sheet.ShowSheet(window);
                    });

                    sheet.InvokeOnMainThread(delegate {
                        sheet.ProgressBarMinValue = 0;
                        sheet.ProgressBarMaxValue = nSelRows.Count;
                    });

                    double conta   = 0;
                    bool   Cancela = false;

                    nuint[] nRows = nSelRows.ToArray();

                    ViewArquivosDataSource datasource = null;
                    TableView.InvokeOnMainThread(delegate
                    {
                        datasource = (ViewArquivosDataSource)TableView.DataSource;
                    });

                    foreach (int lRow in nRows)
                    {
                        string NomeArq = datasource.ViewArquivos [lRow].Nome;

                        ++conta;

                        sheet.InvokeOnMainThread(delegate {
                            sheet.LabelArqValue    = "Extraindo arquivo: " + NomeArq;
                            sheet.ProgressBarValue = conta;
                        });

                        string[] launchArgs = { "x", rarFile, NomeArq, extractPath };
                        NSPipe   pipeOut    = new NSPipe();
                        NSTask   t          = new NSTask();
                        t.LaunchPath     = txtRAR;
                        t.Arguments      = launchArgs;
                        t.StandardOutput = pipeOut;
                        t.Launch();
                        t.WaitUntilExit();

                        //string txtRET = pipeOut.ReadHandle.ReadDataToEndOfFile ().ToString ();

                        sheet.InvokeOnMainThread(delegate {
                            Cancela = sheet.Canceled;
                        });
                        if (Cancela)
                        {
                            break;
                        }
                    }

                    sheet.InvokeOnMainThread(delegate {
                        sheet.CloseSheet();
                        sheet = null;
                    });

                    if (!Cancela)
                    {
                        TableView.InvokeOnMainThread(delegate {
                            NSAlert alert = new NSAlert()
                            {
                                AlertStyle      = NSAlertStyle.Informational,
                                InformativeText = "Arquivo(s) extraido(s) com sucesso !",
                                MessageText     = "Extrair arquivos",
                            };
                            alert.RunSheetModal(window);
                        });
                    }
                }
            }
        }