Fixed (again) how the Add, Edit, Remove, and Send buttons are enabled/disabled
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 /*
2  * Copyright (c) 2011-2014, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31 */
32 using Gee;
33 using Gtk;
34
35 #if IPC_DBUS
36 [DBus (name = "org.janet.Moonshot")]
37 interface IIdentityManager : GLib.Object {
38 #if IPC_DBUS_GLIB
39     public abstract bool show_ui() throws DBus.Error;
40 #else
41     public abstract bool show_ui() throws IOError;
42 #endif
43 }
44 #endif
45
46
47 public class IdentityManagerApp {
48     public static MoonshotLogger logger = get_logger("IdentityManagerApp");
49
50     public IdentityManagerModel model;
51     public IdCard default_id_card;
52     public bool explicitly_launched;
53     public IdentityManagerView view;
54     private MoonshotServer ipc_server;
55     private bool name_is_owned;
56     private bool show_requested;
57
58 #if OS_MACOS
59     public OSXApplication osxApp;
60   
61     // the signal handler function.
62     // the current instance of our app class is passed in the 
63     // id_manager_app_instanceparameter 
64     public static bool on_osx_open_files(OSXApplication osx_app_instance, 
65                                          string file_name, 
66                                          IdentityManagerApp id_manager_app_instance ) {
67         int added_cards = id_manager_app_instance.ipc_server.install_from_file(file_name);
68         return true;
69     }
70 #endif
71
72     /** If we're successfully registered with DBus, then show the UI. Otherwise, wait until we're registered. */
73     public void show() {
74         if (name_is_owned) {
75             if (view != null) {
76                 view.make_visible();
77             }
78         }
79         else {
80             show_requested = true;
81         }
82     }
83     
84 #if LOG4VALA
85     // Call this from main() to ensure that the logger is initialized
86     internal IdentityManagerApp.dummy() {}
87 #endif
88
89     public IdentityManagerApp(bool headless, bool use_flat_file_store) {
90         use_flat_file_store |= UserForcesFlatFileStore();
91
92 #if GNOME_KEYRING
93         bool keyring_available = (!use_flat_file_store) && GnomeKeyring.is_available();
94 #else
95         bool keyring_available = false;
96 #endif
97
98         IIdentityCardStore.StoreType store_type;
99         if (headless || use_flat_file_store || !keyring_available)
100             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
101         else
102             store_type = IIdentityCardStore.StoreType.KEYRING;
103
104         model = new IdentityManagerModel(this, store_type);
105         /* if headless, but we have nothing in the flat file store
106          * and keyring is available, switch to keyring */
107         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
108             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
109
110         if (!headless)
111             view = new IdentityManagerView(this);
112         LinkedList<IdCard> card_list = model.get_card_list();
113         if (card_list.size > 0)
114             this.default_id_card = card_list.last();
115
116         init_ipc_server();
117
118 #if OS_MACOS
119         osxApp = OSXApplication.get_instance();
120         // The 'correct' way of connecting won't work in Mac OS with Vala 0.12; e.g.
121         //     osxApp.ns_application_open_file.connect(install_from_file);
122         // so we have to use this old way
123         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
124 #endif
125     }
126
127     public bool add_identity(IdCard id, bool force_flat_file_store) {
128         if (view != null) return view.add_identity(id, force_flat_file_store);
129         model.add_card(id, force_flat_file_store);
130         return true;
131     }
132
133     public void select_identity(IdentityRequest request) {
134         logger.trace("select_identity");
135
136         IdCard identity = null;
137
138         if (request.select_default)
139         {
140             identity = default_id_card;
141         }
142
143         if (identity == null)
144         {
145             bool has_nai = request.nai != null && request.nai != "";
146             bool has_srv = request.service != null && request.service != "";
147             bool confirm = false;
148
149             foreach (IdCard id in model.get_card_list())
150             {
151                 /* If NAI matches, use this id card */
152                 if (has_nai && request.nai == id.nai)
153                 {
154                     identity = id;
155                     break;
156                 }
157
158                 /* If any service matches we add id card to the candidate list */
159                 if (has_srv)
160                 {
161                     foreach (string srv in id.services)
162                     {
163                         if (request.service == srv)
164                         {
165                             request.candidates.append(id);
166                             continue;
167                         }
168                     }
169                 }
170             }
171
172             /* If more than one candidate we dissasociate service from all ids */
173             if ((identity == null) && has_srv && request.candidates.length() > 1)
174             {
175                 foreach (IdCard id in request.candidates)
176                 {
177                     int i = 0;
178                     SList<string> services_list = null;
179                     bool has_service = false;
180
181                     foreach (string srv in id.services)
182                     {
183                         if (srv == request.service)
184                         {
185                             has_service = true;
186                             continue;
187                         }
188                         services_list.append(srv);
189                     }
190                     
191                     if (!has_service)
192                         continue;
193
194                     if (services_list.length() == 0)
195                     {
196                         id.services = {};
197                         continue;
198                     }
199
200                     string[] services = new string[services_list.length()];
201                     foreach (string srv in services_list)
202                     {
203                         services[i] = srv;
204                         i++;
205                     }
206
207                     id.services = services;
208                 }
209             }
210
211             /* If there are no candidates we use the service matching rules */
212             if ((identity == null) && (request.candidates.length() == 0))
213             {
214                 foreach (IdCard id in model.get_card_list())
215                 {
216                     foreach (Rule rule in id.rules)
217                     {
218                         if (!match_service_pattern(request.service, rule.pattern))
219                             continue;
220
221                         request.candidates.append(id);
222
223                         if (rule.always_confirm == "true")
224                             confirm = true;
225                     }
226                 }
227             }
228             
229             if ((identity == null) && has_nai) {
230                 // create a temp identity
231                 string[] components = request.nai.split("@", 2);
232                 identity = new IdCard();
233                 identity.display_name = request.nai;
234                 identity.username = components[0];
235                 if (components.length > 1)
236                     identity.issuer = components[1];
237                 identity.password = request.password;
238                 identity.temporary = true;
239             }
240             if (identity == null) {
241                 if (request.candidates.length() != 1) {
242                     logger.trace("select_identity: Have %u candidates; user must make selection.".printf(request.candidates.length()));
243                     confirm = true;
244                 } else {
245                     identity = request.candidates.nth_data(0);                    
246                 }
247             }
248
249             if (confirm && (view != null))
250             {
251                 if (!explicitly_launched)
252                     show();
253                 view.queue_identity_request(request);
254                 return;
255             }
256         }
257         // Send back the identity (we can't directly run the
258         // callback because we may be being called from a 'yield')
259         GLib.Idle.add(
260             () => {
261                 if (view != null) {
262                     logger.trace("select_identity (Idle handler): calling check_add_password");
263                     identity = view.check_add_password(identity, request, model);
264                 }
265                 request.return_identity(identity);
266 // The following occasionally causes the app to exit without sending the dbus
267 // reply, so for now we just don't exit
268 //                if (!explicitly_launched)
269 //                    Idle.add(() => { Gtk.main_quit(); return false; } );
270                 return false;
271             }
272             );
273         return;
274     }
275
276     private bool match_service_pattern(string service, string pattern) {
277         var pspec = new PatternSpec(pattern);
278         return pspec.match_string(service);
279     }   
280     
281 #if IPC_MSRPC
282     private void init_ipc_server() {
283         // Errors will currently be sent via g_log - ie. to an
284         // obtrusive message box, on Windows
285         //
286         this.ipc_server = MoonshotServer.get_instance();
287         MoonshotServer.start(this);
288     }
289 #elif IPC_DBUS_GLIB
290     private void init_ipc_server() {
291         try {
292             var conn = DBus.Bus.get(DBus.BusType.SESSION);
293             dynamic DBus.Object bus = conn.get_object("org.freedesktop.DBus",
294                                                       "/org/freedesktop/DBus",
295                                                       "org.freedesktop.DBus");
296
297             // try to register service in session bus
298             uint reply = bus.request_name("org.janet.Moonshot", (uint) 0);
299             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
300             {
301                 this.ipc_server = new MoonshotServer(this);
302                 logger.trace("init_ipc_server(IPC_DBUS_GLIB) : Constructed new MoonshotServer");
303                 conn.register_object("/org/janet/moonshot", ipc_server);
304             } else {
305                 logger.trace("init_ipc_server: reply != PRIMARY_OWNER");
306                 bool shown = false;
307                 GLib.Error e;
308                 DBus.Object manager_proxy = conn.get_object("org.janet.Moonshot",
309                                                             "/org/janet/moonshot",
310                                                             "org.janet.Moonshot");
311                 if (manager_proxy != null)
312                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
313
314                 if (!shown) {
315                     GLib.error("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
316                 } else {
317                     stdout.printf("Showed previously launched identity manager.\n");
318                     GLib.Process.exit(0);
319                 }
320             }
321         }
322         catch (DBus.Error e)
323         {
324             logger.trace("bus_acquired_cb");
325             try {
326                 conn.register_object ("/org/janet/moonshot", ipc_server);
327             }
328             catch (Error e)
329             {
330                 stderr.printf ("%s\n", e.message);
331                 logger.error("bus_acquired_cb: Caught error: " + e.message);
332             }
333         }
334     }
335 #else
336     private void bus_acquired_cb(DBusConnection conn) {
337         logger.trace("bus_acquired_cb");
338         try {
339             conn.register_object("/org/janet/moonshot", ipc_server);
340         }
341         catch (Error e)
342         {
343             this.ipc_server = new MoonshotServer (this);
344             logger.trace("init_ipc_server: Constructed new MoonshotServer");
345             GLib.Bus.own_name (GLib.BusType.SESSION,
346                                "org.janet.Moonshot",
347                                GLib.BusNameOwnerFlags.NONE,
348                                bus_acquired_cb,
349                                (conn, name) => {logger.trace("init_ipc_server: name_acquired_closure");},
350                                (conn, name) => {
351                                    logger.trace("init_ipc_server: name_lost_closure");
352                                    bool shown=false;
353                                    try {
354                                        IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
355                                        shown = manager.show_ui();
356                                    } catch (IOError e) {
357                                        logger.error("init_ipc_server.name_lost_closure: Caught error: ");
358                                    }
359                                    if (!shown) {
360                                        logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
361                                        GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
362                                    } else {
363                                        logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
364                                        stdout.printf("Showed previously launched identity manager.\n");
365                                        GLib.Process.exit(0);
366                                    }
367                                });
368         }
369     }
370
371     private void init_ipc_server() {
372         this.ipc_server = new MoonshotServer(this);
373         bool shown = false;
374         GLib.Bus.own_name(GLib.BusType.SESSION,
375                           "org.janet.Moonshot",
376                           GLib.BusNameOwnerFlags.NONE,
377                           bus_acquired_cb,
378
379                           // Name acquired callback:
380                           (conn, name) => {
381                               logger.trace(@"init_ipc_server: name_acquired_closure; show_requested=$show_requested");
382
383                               name_is_owned = true;
384
385                               // Now that we know that we own the name, it's safe to show the UI.
386                               if (show_requested) {
387                                   show();
388                                   show_requested = false;
389                               }
390                               shown = true;
391                           },
392
393                           // Name lost callback:
394                           (conn, name) => {
395                               logger.trace("init_ipc_server: name_lost_closure");
396
397                               // This callback usually means that another moonshot is already running.
398                               // But it *might* mean that we lost the name for some other reason
399                               // (though it's unclear to me yet what those reasons are.)
400                               // Clearing these flags seems like a good idea for that case. -- dbreslau
401                               name_is_owned = false;
402                               show_requested = false;
403
404                               try {
405                                   if (!shown) {
406                                       IIdentityManager manager = Bus.get_proxy_sync(BusType.SESSION, name, "/org/janet/moonshot");
407                                       shown = manager.show_ui();
408                                   }
409                               } catch (IOError e) {
410                                   logger.error("init_ipc_server.name_lost_closure: Caught IOError: " + e.message);
411                               }
412                               if (!shown) {
413                                   logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
414                                   GLib.error("Couldn't own name %s on dbus or show previously launched identity manager.", name);
415                               } else {
416                                   logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
417                                   stdout.printf("Showed previously launched identity manager.\n");
418                                   GLib.Process.exit(0);
419                               }
420                           });
421     }
422 #endif
423 }
424
425 static bool explicitly_launched = true;
426 static bool use_flat_file_store = false;
427 const GLib.OptionEntry[] options = {
428     {"dbus-launched", 0, GLib.OptionFlags.REVERSE, GLib.OptionArg.NONE,
429      ref explicitly_launched, "launch for dbus rpc use", null},
430     {"flat-file-store", 0, 0, GLib.OptionArg.NONE,
431      ref use_flat_file_store, "force use of flat file identity store (used by default only for headless operation)", null},
432     {null}
433 };
434
435
436 public static int main(string[] args) {
437
438 #if LOG4VALA
439     new IdentityManagerApp.dummy();
440 #endif
441
442 #if IPC_MSRPC
443     bool headless = false;
444 #else
445     bool headless = GLib.Environment.get_variable("DISPLAY") == null;
446 #endif
447
448     if (headless) {
449         try {
450             var opt_context = new OptionContext(null);
451             opt_context.set_help_enabled(true);
452             opt_context.add_main_entries(options, null);
453             opt_context.parse(ref args);
454         } catch (OptionError e) {
455             stdout.printf(_("error: %s\n"),e.message);
456             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
457             return -1;
458         }
459         explicitly_launched = false;
460     } else {
461         try {
462             if (!Gtk.init_with_args(ref args, _(""), options, null)) {
463                 stdout.printf(_("unable to initialize window\n"));
464                 return -1;
465             }
466         } catch (GLib.Error e) {
467             stdout.printf(_("error: %s\n"),e.message);
468             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
469             return -1;
470         }
471         gtk_available = true;
472     }
473
474 #if OS_WIN32
475     // Force specific theme settings on Windows without requiring a gtkrc file
476     Gtk.Settings settings = Gtk.Settings.get_default();
477     settings.set_string_property("gtk-theme-name", "ms-windows", "moonshot");
478     settings.set_long_property("gtk-menu-images", 0, "moonshot");
479 #endif
480
481     Intl.bindtextdomain(Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
482     Intl.bind_textdomain_codeset(Config.GETTEXT_PACKAGE, "UTF-8");
483     Intl.textdomain(Config.GETTEXT_PACKAGE);
484        
485        
486     var app = new IdentityManagerApp(headless, use_flat_file_store);
487     app.explicitly_launched = explicitly_launched;
488     IdentityManagerApp.logger.trace(@"main: explicitly_launched=$explicitly_launched");
489         
490     if (app.explicitly_launched) {
491         app.show();
492     }
493
494     if (headless) {
495 #if !IPC_MSRPC
496         MainLoop loop = new MainLoop();
497         loop.run();
498 #endif
499     }
500     else {
501         Gtk.main();
502     }
503
504     return 0;
505 }
506