Welcome to mirror list, hosted at ThFree Co, Russian Federation.

RumpsRunner.cs « Duplicati.GUI.TrayIcon « GUI « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 68a9b7be5c096f365c34fd565d11021afcadbabe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//  Copyright (C) 2015, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using CoCoL;

namespace Duplicati.GUI.TrayIcon
{
    public class RumpsRunner : TrayIconBase
    {
        private class MenuItemWrapper : Duplicati.GUI.TrayIcon.IMenuItem
        {

            private RumpsRunner m_parent;

            private string m_text;
            private MenuIcons m_icon;
            private bool m_enabled;
            private bool m_default;

            public MenuItemWrapper(RumpsRunner parent, string text, Duplicati.GUI.TrayIcon.MenuIcons icon, Action callback, IList<Duplicati.GUI.TrayIcon.IMenuItem> subitems)
            {
                m_parent = parent;
                Key = Guid.NewGuid().ToString("N");
                m_text = text ?? "";
                Callback = callback;
                m_enabled = true;
                m_default = false;
                if (subitems != null)
                    Subitems = subitems.Cast<MenuItemWrapper>().ToList();
            }

            [JsonIgnore]
            public Action Callback { get; private set; }

            public string Key { get; private set; }

            public IList<MenuItemWrapper> Subitems { get; private set; }
            
            #region IMenuItem implementation
            public string Text
            {
                get { return m_text; }
                set
                {
                    if (m_text != value)
                    {
                        m_text = value;
                        m_parent.UpdateMenu(this);
                    }
                }
            }
            public MenuIcons Icon
            {
                get { return m_icon; }
                set
                {
                    if (m_icon != value)
                    {
                        m_icon = value;
                        m_parent.UpdateMenu(this);
                    }
                }
            }
            public bool Enabled
            {
                get { return m_enabled; }
                set
                {
                    if (m_enabled != value)
                    {
                        m_enabled = value;
                        m_parent.UpdateMenu(this);
                    }
                }
            }
            public bool Default
            {
                get { return m_default; }
                set
                {
                    if (m_default != value)
                    {
                        m_default = value;
                        m_parent.UpdateMenu(this);
                    }
                }
            }
            #endregion
        }

        private static readonly System.Reflection.Assembly ASSEMBLY = System.Reflection.Assembly.GetExecutingAssembly();
        private static readonly string ICON_PATH = ASSEMBLY.GetName().Name + ".OSX_Icons.";

        private static readonly string ICON_NORMAL = ICON_PATH + "normal.png";
        private static readonly string ICON_PAUSED = ICON_PATH + "normal-pause.png";
        private static readonly string ICON_RUNNING = ICON_PATH + "normal-running.png";
        private static readonly string ICON_ERROR = ICON_PATH + "normal-error.png";

        private Dictionary<Duplicati.GUI.TrayIcon.TrayIcons, string> m_images = new Dictionary<Duplicati.GUI.TrayIcon.TrayIcons, string>();

        private System.Diagnostics.Process m_rumpsProcess;

        private static readonly string RUMPS_PYTHON = string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("RUMPS_PYTHON")) ? "/usr/bin/python2.7" : Environment.GetEnvironmentVariable("RUMPS_PYTHON");

        private static readonly string SCRIPT_PATH = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "OSXTrayHost", "osx-trayicon-rumps.py");
        private IsolatedChannelScope m_scope;
        private IWriteChannelEnd<string> m_toRumps;
        private List<MenuItemWrapper> m_menus;
        private bool m_isQuitting = false;
        private TrayIcons m_lastIcon;

        public static bool CanRun()
        {
            if (!Library.Utility.Utility.IsClientOSX)
                return false;
            
            if (!File.Exists(SCRIPT_PATH) || !File.Exists(RUMPS_PYTHON))
                return false;

            try
            {
                var si = System.Diagnostics.Process.Start(RUMPS_PYTHON, string.Format("\"{0}\" TEST", SCRIPT_PATH));
                si.WaitForExit((int)TimeSpan.FromSeconds(5).TotalMilliseconds);
                if (!si.HasExited)
                {
                    si.Kill();
                    return false;
                }

                return si.ExitCode == 0;
            }
            catch
            {
            }

            return false;
        }

        private void ResetMenus()
        {
            m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "setmenus", Menus = m_menus}));
        }

        private void Restart()
        {
            if (m_toRumps != null)
                m_toRumps.Dispose();
            
            var startinfo = new System.Diagnostics.ProcessStartInfo(RUMPS_PYTHON, string.Format("\"{0}\"", SCRIPT_PATH));
            startinfo.CreateNoWindow = true;
            startinfo.UseShellExecute = false;
            startinfo.RedirectStandardInput = true;
            startinfo.RedirectStandardOutput = true;
            startinfo.RedirectStandardError = true;

            m_rumpsProcess = System.Diagnostics.Process.Start(startinfo);
            var ch = ChannelManager.CreateChannel<string>();
            m_toRumps = ch.AsWriteOnly();

            WriteChannel(m_rumpsProcess.StandardInput, ch.AsReadOnly());
            ReadChannel(m_rumpsProcess.StandardOutput);
            ReadChannel(m_rumpsProcess.StandardError);

            m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "background"}));
            //m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "setappicon", Image = GetIcon(m_lastIcon)}));

            if (m_menus != null)
            {
                ResetMenus();
                m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "seticon", Image = GetIcon(m_lastIcon)}));
            }
        }

        public override void Init(string[] args)
        {
            m_scope = new IsolatedChannelScope();
            Restart();

            base.Init(args);
        }

        private static Task WriteChannel(StreamWriter stream, IReadChannelEnd<string> ch)
        {
            stream.AutoFlush = true;

            return AutomationExtensions.RunTask(
                new {
                    Input = ch
                },
                async self =>
                {
                    using(stream)
                    {
                        while(true)
                        {
                            var line = await self.Input.ReadAsync();
                            await stream.WriteLineAsync(line);
                            //Console.WriteLine("Wrote {0}", line);
                        }
                    }
                }
            );
        }

        private async Task ReadChannel(StreamReader stream)
        {
            string line;
            using(stream)
                while ((line = await stream.ReadLineAsync()) != null)
                {
                    //Console.WriteLine("Got message: {0}", line);

                    line = line.Trim();
                    if (line.StartsWith("click:", StringComparison.OrdinalIgnoreCase))
                    {
                        var key = line.Substring("click:".Length);
                        var menu = m_menus.Where(x => string.Equals(x.Key, key)).FirstOrDefault();
                        if (menu == null)
                        {
                            Console.WriteLine("Menu not found: {0}", key);
                        }
                        else
                        {
                            menu.Callback();
                        }
                    }
                    else if (!line.StartsWith("info") && !string.IsNullOrWhiteSpace(line))
                    {
                        Console.WriteLine("Unexpected message: {0}", line);
                    }
                            
                }
        }

        private void UpdateMenu(MenuItemWrapper menu)
        {
            if (m_menus != null)
                m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "setmenu", Menu = menu}));
        }

        private string LoadStream(System.IO.Stream s)
        {
            using(var ms = new MemoryStream())
            {
                s.CopyTo(ms);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        protected override void Run(string[] args)
        {
            m_rumpsProcess.WaitForExit();
            while(!m_isQuitting)
            {
                Restart();
                m_rumpsProcess.WaitForExit();
            }
        }

        protected override void UpdateUIState(Action action)
        {
            action();
        }

        private string GetIcon(Duplicati.GUI.TrayIcon.TrayIcons icon)
        {
            if (!m_images.ContainsKey(icon))
            {
                switch(icon)
                {
                    case Duplicati.GUI.TrayIcon.TrayIcons.IdleError:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_ERROR));
                        break;
                    case Duplicati.GUI.TrayIcon.TrayIcons.Paused:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_PAUSED));
                        break;
                    case Duplicati.GUI.TrayIcon.TrayIcons.PausedError:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_PAUSED));
                        break;
                    case Duplicati.GUI.TrayIcon.TrayIcons.Running:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_RUNNING));
                        break;
                    case Duplicati.GUI.TrayIcon.TrayIcons.RunningError:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_RUNNING));
                        break;
                    case Duplicati.GUI.TrayIcon.TrayIcons.Idle:
                    default:
                        m_images[icon] = LoadStream(ASSEMBLY.GetManifestResourceStream(ICON_NORMAL));
                        break;
                }
            }

            return m_images[icon];
        }

        protected override Duplicati.GUI.TrayIcon.TrayIcons Icon 
        {
            set 
            {
                m_lastIcon = value;
                m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "seticon", Image = GetIcon(value)}));
            }
        }

        protected override Duplicati.GUI.TrayIcon.IMenuItem CreateMenuItem (string text, Duplicati.GUI.TrayIcon.MenuIcons icon, Action callback, System.Collections.Generic.IList<Duplicati.GUI.TrayIcon.IMenuItem> subitems)
        {
            return new MenuItemWrapper(this, text, icon, callback, subitems);
        }

        protected override void Exit()
        {
            m_isQuitting = true;
            if (m_rumpsProcess != null && !m_rumpsProcess.HasExited)
            {
                m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "shutdown"}));
                if (m_toRumps != null)
                {
                    m_toRumps.Dispose();
                    m_toRumps = null;
                }

                m_rumpsProcess.WaitForExit((int)TimeSpan.FromSeconds(5).TotalMilliseconds);
                m_rumpsProcess.Kill();
                m_rumpsProcess = null;
            }

        }

        protected override void SetMenu(System.Collections.Generic.IEnumerable<Duplicati.GUI.TrayIcon.IMenuItem> items)
        {
            m_menus = items.Cast<MenuItemWrapper>().ToList();

            ResetMenus();
        }

        protected override void NotifyUser(string title, string message, NotificationType type)
        {
            m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "notification", Title = title, Message = message}));
        }

        public override void Dispose()
        {
            if (m_scope != null)
                m_scope.Dispose();
        }
    }
}