4237319ad878be6a6b5a197853d404c7a2939bb6
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 using Gee;
2 using Gtk;
3
4 #if IPC_DBUS
5 [DBus (name = "org.janet.Moonshot")]
6 interface IIdentityManager : GLib.Object {
7 #if IPC_DBUS_GLIB
8     public abstract bool show_ui() throws DBus.Error;
9 #else
10     public abstract bool show_ui() throws IOError;
11 #endif
12 }
13 #endif
14
15 public class IdentityManagerApp {
16     public IdentityManagerModel model;
17     public IdCard default_id_card;
18     public bool explicitly_launched;
19     public IdentityManagerView view;
20     private MoonshotServer ipc_server;
21
22 #if OS_MACOS
23         public OSXApplication osxApp;
24   
25     // the signal handler function.
26     // the current instance of our app class is passed in the 
27     // id_manager_app_instanceparameter 
28         public static bool on_osx_open_files (OSXApplication osx_app_instance, 
29                                         string file_name, 
30                                         IdentityManagerApp id_manager_app_instance ) {
31     int added_cards = id_manager_app_instance.ipc_server.install_from_file(file_name);
32     return true;
33         }
34 #endif
35
36     private const int WINDOW_WIDTH = 400;
37     private const int WINDOW_HEIGHT = 500;
38     public void show() {
39         if (view != null) view.show();    
40     }
41         
42     public IdentityManagerApp (bool headless, bool use_flat_file_store) {
43 #if GNOME_KEYRING
44         bool keyring_available = GnomeKeyring.is_available();
45 #else
46         bool keyring_available = false;
47 #endif
48         IIdentityCardStore.StoreType store_type;
49         if (headless || use_flat_file_store || !keyring_available)
50             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
51         else
52             store_type = IIdentityCardStore.StoreType.KEYRING;
53
54         model = new IdentityManagerModel(this, store_type);
55         /* if headless, but we have nothing in the flat file store
56          * and keyring is available, switch to keyring */
57         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
58             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
59
60         if (!headless)
61             view = new IdentityManagerView(this);
62         LinkedList<IdCard> card_list = model.get_card_list() ;
63         if (card_list.size > 0)
64             this.default_id_card = card_list.first();
65
66         init_ipc_server ();
67
68 #if OS_MACOS
69
70         osxApp = OSXApplication.get_instance();
71         // The 'correct' way of connrcting wont work in Mac OS with Vala 0.12   e.g.    
72         //              osxApp.ns_application_open_file.connect(install_from_file);
73         // so we have to use this old way
74         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
75
76 #endif
77     }
78
79     public bool add_identity (IdCard id) {
80         if (view != null) return view.add_identity(id);
81         model.add_card(id);
82         return true;
83     }
84
85     public void select_identity (IdentityRequest request) {
86         IdCard identity = null;
87
88         if (request.select_default)
89         {
90             identity = default_id_card;
91         }
92
93         if (identity == null)
94         {
95             bool has_nai = request.nai != null && request.nai != "";
96             bool has_srv = request.service != null && request.service != "";
97             bool confirm = false;
98             IdCard nai_provided = null;
99
100             foreach (IdCard id in model.get_card_list())
101             {
102                 /* If NAI matches we add id card to the candidate list */
103                 if (has_nai && request.nai == id.nai)
104                 {
105                     nai_provided = id;
106                     request.candidates.append (id);
107                     continue;
108                 }
109
110                 /* If any service matches we add id card to the candidate list */
111                 if (has_srv)
112                 {
113                     foreach (string srv in id.services)
114                     {
115                         if (request.service == srv)
116                         {
117                             request.candidates.append (id);
118                             continue;
119                         }
120                     }
121                 }
122             }
123
124             /* If more than one candidate we dissasociate service from all ids */
125             if (has_srv && request.candidates.length() > 1)
126             {
127                 foreach (IdCard id in request.candidates)
128                 {
129                     int i = 0;
130                     SList<string> services_list = null;
131                     bool has_service = false;
132
133                     foreach (string srv in id.services)
134                     {
135                         if (srv == request.service)
136                         {
137                             has_service = true;
138                             continue;
139                         }
140                         services_list.append (srv);
141                     }
142                     
143                     if (!has_service)
144                         continue;
145
146                     if (services_list.length () == 0)
147                     {
148                         id.services = {};
149                         continue;
150                     }
151
152                     string[] services = new string[services_list.length ()];
153                     foreach (string srv in services_list)
154                     {
155                         services[i] = srv;
156                         i++;
157                     }
158
159                     id.services = services;
160                 }
161             }
162
163 //            model.store_id_cards ();
164
165             /* If there are no candidates we use the service matching rules */
166             if (request.candidates.length () == 0)
167             {
168                 foreach (IdCard id in model.get_card_list())
169                 {
170                     foreach (Rule rule in id.rules)
171                     {
172                         if (!match_service_pattern (request.service, rule.pattern))
173                             continue;
174
175                         request.candidates.append (id);
176
177                         if (rule.always_confirm == "true")
178                             confirm = true;
179                     }
180                 }
181             }
182             
183             if (request.candidates.length () > 1)
184             {
185                 if (has_nai && nai_provided != null)
186                 {
187                     identity = nai_provided;
188                     confirm = false;
189                 }
190                 else
191                     confirm = true;
192             }
193             if (identity == null)
194                 identity = request.candidates.nth_data (0);
195             if (identity == null)
196                 confirm = true;
197
198             /* TODO: If candidate list empty return fail */
199             
200             if (confirm && (view != null))
201             {
202                 if (!explicitly_launched)
203                     show();
204                 view.queue_identity_request(request);
205                 return;
206             }
207         }
208         // Send back the identity (we can't directly run the
209         // callback because we may be being called from a 'yield')
210         Idle.add(
211             () => {
212                 request.return_identity (identity);
213 // The following occasionally causes the app to exit without sending the dbus
214 // reply, so for now we just don't exit
215 //                if (!explicitly_launched)
216 //                    Idle.add( () => { Gtk.main_quit(); return false; } );
217                 return false;
218             }
219         );
220         return;
221     }
222
223     private bool match_service_pattern (string service, string pattern)
224     {
225         var pspec = new PatternSpec (pattern);
226         return pspec.match_string (service);
227     }   
228     
229 #if IPC_MSRPC
230     private void init_ipc_server ()
231     {
232         // Errors will currently be sent via g_log - ie. to an
233         // obtrusive message box, on Windows
234         //
235         this.ipc_server = MoonshotServer.get_instance ();
236         MoonshotServer.start (this);
237     }
238 #elif IPC_DBUS_GLIB
239     private void init_ipc_server ()
240     {
241         try {
242             var conn = DBus.Bus.get (DBus.BusType.SESSION);
243             dynamic DBus.Object bus = conn.get_object ("org.freedesktop.DBus",
244                                                        "/org/freedesktop/DBus",
245                                                        "org.freedesktop.DBus");
246
247             // try to register service in session bus
248             uint reply = bus.request_name ("org.janet.Moonshot", (uint) 0);
249             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
250             {
251                 this.ipc_server = new MoonshotServer (this);
252                 conn.register_object ("/org/janet/moonshot", ipc_server);
253             } else {
254                 bool shown=false;
255                 GLib.Error e;
256                 DBus.Object manager_proxy = conn.get_object ("org.janet.Moonshot",
257                                                              "/org/janet/moonshot",
258                                                              "org.janet.Moonshot");
259                 if (manager_proxy != null)
260                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
261
262                 if (!shown) {
263                     GLib.error ("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
264                 } else {
265                     stdout.printf("Showed previously launched identity manager.\n");
266                     GLib.Process.exit(0);
267                 }
268             }
269         }
270         catch (DBus.Error e)
271         {
272             stderr.printf ("%s\n", e.message);
273         }
274     }
275 #else
276     private void bus_acquired_cb (DBusConnection conn)
277     {
278         try {
279             conn.register_object ("/org/janet/moonshot", ipc_server);
280         }
281         catch (Error e)
282         {
283             stderr.printf ("%s\n", e.message);
284         }
285     }
286
287     private void init_ipc_server ()
288     {
289         this.ipc_server = new MoonshotServer (this);
290         GLib.Bus.own_name (GLib.BusType.SESSION,
291                            "org.janet.Moonshot",
292                            GLib.BusNameOwnerFlags.NONE,
293                            bus_acquired_cb,
294                            (conn, name) => {},
295                            (conn, name) => {
296                                bool shown=false;
297                                try {
298                                    IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
299                                    shown = manager.show_ui();
300                                } catch (IOError e) {
301                                }
302                                if (!shown) {
303                                    GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
304                                } else {
305                                    stdout.printf("Showed previously launched identity manager.\n");
306                                    GLib.Process.exit(0);
307                                }
308                            });
309     }
310 #endif
311 }
312
313 static bool explicitly_launched = true;
314 static bool use_flat_file_store = false;
315 const GLib.OptionEntry[] options = {
316     {"DBusLaunch",0,GLib.OptionFlags.REVERSE,GLib.OptionArg.NONE,
317      ref explicitly_launched,"launch for dbus rpc use",null},
318     {"FlatFileStore",0,0,GLib.OptionArg.NONE,
319      ref use_flat_file_store,"force use of flat file identity store (used by default only for headless operation)",null},
320     {null}
321 };
322
323
324 public static int main(string[] args){
325 #if IPC_MSRPC
326         bool headless = false;
327 #else
328         bool headless = GLib.Environment.get_variable("DISPLAY") == null;
329 #endif
330
331         if (headless) {
332             explicitly_launched = false;
333         } else {
334             try {
335                 Gtk.init_with_args(ref args, _(""), options, null);
336             } catch (GLib.Error e) {
337                 stdout.printf(_("error: %s\n"),e.message);
338                 stdout.printf(_("Run '%s --help' to see a full list of available options"), args[0]);
339             }
340         }
341
342 #if OS_WIN32
343         // Force specific theme settings on Windows without requiring a gtkrc file
344         Gtk.Settings settings = Gtk.Settings.get_default ();
345         settings.set_string_property ("gtk-theme-name", "ms-windows", "moonshot");
346         settings.set_long_property ("gtk-menu-images", 0, "moonshot");
347 #endif
348
349         Intl.bindtextdomain (Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
350         Intl.bind_textdomain_codeset (Config.GETTEXT_PACKAGE, "UTF-8");
351         Intl.textdomain (Config.GETTEXT_PACKAGE);
352        
353            
354         var app = new IdentityManagerApp(headless, use_flat_file_store);
355         app.explicitly_launched = explicitly_launched;
356         
357         if (app.explicitly_launched) {
358             app.show();
359         }
360
361         if (headless) {
362 #if !IPC_MSRPC
363             MainLoop loop = new MainLoop();
364             loop.run();
365 #endif
366         } else {
367             Gtk.main();
368         }
369
370         return 0;
371     }
372