1/*
2    Copyright 2013 Julien Lavergne <gilir@ubuntu.com>
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17using Gtk;
18
19namespace LDefaultApps
20{
21    public string read_autostart_conf ()
22    {
23        string config_path;
24        config_path = get_config_home_path("autostart");
25        var config_file = File.new_for_path (config_path);
26        if (!config_file.query_exists ())
27        {
28            string config_system_path;
29            config_system_path = get_config_path("autostart");
30
31            if (config_system_path == null)
32            {
33                /* No system file and no home file, create a blank file in home */
34                try
35                {
36                    message("Create blank file");
37                    File blank_file = File.new_for_path (config_path);
38		            blank_file.create (FileCreateFlags.PRIVATE);
39                }
40                catch (GLib.Error e)
41                {
42                    message (e.message);
43                }
44            }
45            else
46            {
47                File file = File.new_for_path (config_system_path);
48                var config_parent = config_file.get_parent();
49
50                if (!config_parent.query_exists ())
51                {
52                    try
53                    {
54                        config_parent.make_directory_with_parents ();
55                    }
56                    catch (GLib.Error e)
57                    {
58                        message (e.message);
59                    }
60                }
61
62               try
63                {
64                    file.copy (config_file, FileCopyFlags.NONE);
65                }
66                catch (GLib.Error e)
67                {
68                    message (e.message);
69                }
70            }
71        }
72        message("Conf file for autostart: %s", config_path);
73        return config_path;
74    }
75
76    public void manual_autostart_init (Builder builder)
77    {
78        if (read_autostart_conf() == null)
79        {
80            message("Can't find an autostart file, abort");
81        }
82        else
83        {
84            FileStream stream = FileStream.open (read_autostart_conf(), "r");
85	        assert (stream != null);
86
87            message ("Autostart conf file : %s", read_autostart_conf());
88
89            var auto_align = builder.get_object("autostart_alignment") as Gtk.Alignment;
90            var auto_vbox = builder.get_object("manual_autostart_vbox") as Gtk.VBox;
91
92            foreach (var widget in auto_vbox.get_children())
93            {
94                auto_vbox.remove(widget);
95            }
96
97	        string? line = null;
98	        while ((line = stream.read_line ()) != null)
99            {
100                message("Autostart line : %s", line);
101                var hbox = new HBox(false, 0);
102                var check = new Gtk.CheckButton.with_label (line);
103                if (line[0:1] == "#")
104                {
105                    check.set_active(false);
106                }
107                else
108                {
109                    check.set_active(true);
110                }
111
112                check.toggled.connect (() => {
113                    message("Label to update : %s", check.get_label());
114                    if (check.get_active())
115                    {
116                        if (check.get_label()[0:1] == "#")
117                        {
118                                update_autostart_conf(check.get_label(), "activate", builder);
119                                message("Activate : %s", check.get_label());
120                        }
121                    }
122                    else
123                    {
124                        if (check.get_label()[0:1] != "#")
125                        {
126                                update_autostart_conf(check.get_label(), "desactivate", builder);
127                                message("Deactivate : %s", check.get_label());
128                        }
129                    }
130                });
131
132		        hbox.pack_start(check, false, false, 0);
133
134                var button = new Button.from_stock("gtk-remove");
135                button.clicked.connect (() => {
136                    update_autostart_conf(check.get_label(), "remove", builder);
137                    message ("try to remove : %s", check.get_label());
138                });
139
140		        hbox.pack_start(button, false, false, 0);
141
142                auto_vbox.pack_start(hbox, false, false, 0);
143	        }
144
145            var add_hbox = new HBox(false, 0);
146            var add_button = new Button.from_stock("gtk-add");
147            var add_entry = new Entry();
148            add_hbox.pack_start(add_button, false, false, 0);
149            add_hbox.pack_start(add_entry, false, false, 0);
150            auto_vbox.pack_start(add_hbox, false, false, 0);
151            auto_align.add(auto_vbox);
152            add_button.clicked.connect (() => {
153                update_autostart_conf(add_entry.get_text(), "add", builder);
154                add_entry.set_text("");
155            });
156
157            auto_vbox.show_all();
158        }
159    }
160
161    public void update_autostart_conf (string line, string action, Builder builder)
162    {
163        var new_line = new StringBuilder ();
164        switch (action)
165        {
166            case ("activate"):
167                new_line.append(line);
168                new_line.erase(0,1);
169                new_line.append("\n");
170                break;
171            case ("desactivate"):
172                new_line.append("#");
173                new_line.append(line);
174                new_line.append("\n");
175                break;
176            case ("add"):
177                new_line.append(line);
178                new_line.append("\n");
179                break;
180            case ("remove"):
181                break;
182        }
183        try
184        {
185            string tmp_path = Path.build_filename(Environment.get_user_cache_dir(), "lxsession-default-apps", "autostart.tmp");
186            var tmp_file = File.new_for_path (tmp_path);
187            var dest_file = File.new_for_path (read_autostart_conf());
188
189            FileStream stream = FileStream.open (read_autostart_conf(), "r");
190            var tmp_stream = new DataOutputStream (tmp_file.create (FileCreateFlags.REPLACE_DESTINATION));
191
192	        assert (stream != null);
193	        string? read = null;
194	        while ((read = stream.read_line ()) != null)
195            {
196                message ("read : %s", read);
197                message ("line : %s", line);
198                if (read == line)
199                {
200                    tmp_stream.put_string(new_line.str);
201                }
202                else
203                {
204                    tmp_stream.put_string(read);
205                    tmp_stream.put_string("\n");
206                }
207            }
208
209            if (action == "add")
210            {
211                tmp_stream.put_string(new_line.str);
212            }
213
214            tmp_file.copy(dest_file, FileCopyFlags.OVERWRITE);
215            tmp_file.delete();
216
217            manual_autostart_init(builder);
218        }
219        catch (GLib.Error e)
220        {
221            message (e.message);
222        }
223
224    }
225
226    public void autostart_core_applications (Builder builder, DbusBackend dbus_backend)
227    {
228        /* TODO Finish this
229        var vbox = builder.get_object("autostart_core_applications") as Gtk.VBox;
230        var item_box = new Gtk.VBox(false, 0);
231        vbox.add(item_box);
232
233        First, applications that are always autostarted (don't accept to disable)
234        string[] list_not_disable = {"windows_manager", "panel"};
235
236        for (int a = 0 ; a < list_not_disable.length ; a++)
237        {
238            string default_text = dbus_backend.Get(list_not_disable[a],"command");
239            if ( default_text != "")
240            {
241                var item_label = new Label(default_text);
242                item_box.add(item_label);
243            }
244
245        }
246
247        vbox.show_all();
248        */
249
250    }
251
252    /* TODO make the 2 following function common, or Dbus, or env, or anything to replace this c&p */
253    public string get_config_home_path (string conf_file)
254    {
255
256        string user_config_dir = Path.build_filename(
257                                 Environment.get_user_config_dir (),
258                                 "lxsession",
259                                 Environment.get_variable("DESKTOP_SESSION"),
260                                 conf_file);
261
262        return user_config_dir;
263
264    }
265
266
267    public string get_config_path (string conf_file) {
268
269        string final_config_file;
270
271        string user_config_dir = get_config_home_path(conf_file);
272
273        if (FileUtils.test (user_config_dir, FileTest.EXISTS))
274        {
275            message ("User config used : %s", user_config_dir);
276            final_config_file = user_config_dir;
277        }
278        else
279        {
280            string[] system_config_dirs = Environment.get_system_config_dirs ();
281            string config_system_location = null;
282            string path_system_config_file = null;
283
284            foreach (string config in (system_config_dirs)) {
285                config_system_location = Path.build_filename (config, "lxsession", Environment.get_variable("DESKTOP_SESSION"));
286                message ("Config system location : %s", config_system_location);
287                if (FileUtils.test (config_system_location, FileTest.EXISTS)) {
288                    path_system_config_file = Path.build_filename (config_system_location, conf_file);
289                    break;
290                }
291            }
292          message ("System system path location : %s", path_system_config_file);
293          final_config_file =  path_system_config_file;
294
295         }
296         message ("Final file used : %s", final_config_file);
297         return final_config_file;
298
299    }
300
301}
302