Fix error when unknown option is specified.
[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, bool force_flat_file_store) {
80         if (view != null) return view.add_identity(id, force_flat_file_store);
81         model.add_card(id, force_flat_file_store);
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                 if (view != null) {
213                     view.check_add_password(identity, request, model);
214                 }
215                 request.return_identity (identity);
216 // The following occasionally causes the app to exit without sending the dbus
217 // reply, so for now we just don't exit
218 //                if (!explicitly_launched)
219 //                    Idle.add( () => { Gtk.main_quit(); return false; } );
220                 return false;
221             }
222         );
223         return;
224     }
225
226     private bool match_service_pattern (string service, string pattern)
227     {
228         var pspec = new PatternSpec (pattern);
229         return pspec.match_string (service);
230     }   
231     
232 #if IPC_MSRPC
233     private void init_ipc_server ()
234     {
235         // Errors will currently be sent via g_log - ie. to an
236         // obtrusive message box, on Windows
237         //
238         this.ipc_server = MoonshotServer.get_instance ();
239         MoonshotServer.start (this);
240     }
241 #elif IPC_DBUS_GLIB
242     private void init_ipc_server ()
243     {
244         try {
245             var conn = DBus.Bus.get (DBus.BusType.SESSION);
246             dynamic DBus.Object bus = conn.get_object ("org.freedesktop.DBus",
247                                                        "/org/freedesktop/DBus",
248                                                        "org.freedesktop.DBus");
249
250             // try to register service in session bus
251             uint reply = bus.request_name ("org.janet.Moonshot", (uint) 0);
252             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
253             {
254                 this.ipc_server = new MoonshotServer (this);
255                 conn.register_object ("/org/janet/moonshot", ipc_server);
256             } else {
257                 bool shown=false;
258                 GLib.Error e;
259                 DBus.Object manager_proxy = conn.get_object ("org.janet.Moonshot",
260                                                              "/org/janet/moonshot",
261                                                              "org.janet.Moonshot");
262                 if (manager_proxy != null)
263                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
264
265                 if (!shown) {
266                     GLib.error ("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
267                 } else {
268                     stdout.printf("Showed previously launched identity manager.\n");
269                     GLib.Process.exit(0);
270                 }
271             }
272         }
273         catch (DBus.Error e)
274         {
275             stderr.printf ("%s\n", e.message);
276         }
277     }
278 #else
279     private void bus_acquired_cb (DBusConnection conn)
280     {
281         try {
282             conn.register_object ("/org/janet/moonshot", ipc_server);
283         }
284         catch (Error e)
285         {
286             stderr.printf ("%s\n", e.message);
287         }
288     }
289
290     private void init_ipc_server ()
291     {
292         this.ipc_server = new MoonshotServer (this);
293         GLib.Bus.own_name (GLib.BusType.SESSION,
294                            "org.janet.Moonshot",
295                            GLib.BusNameOwnerFlags.NONE,
296                            bus_acquired_cb,
297                            (conn, name) => {},
298                            (conn, name) => {
299                                bool shown=false;
300                                try {
301                                    IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
302                                    shown = manager.show_ui();
303                                } catch (IOError e) {
304                                }
305                                if (!shown) {
306                                    GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
307                                } else {
308                                    stdout.printf("Showed previously launched identity manager.\n");
309                                    GLib.Process.exit(0);
310                                }
311                            });
312     }
313 #endif
314 }
315
316 static bool explicitly_launched = true;
317 static bool use_flat_file_store = false;
318 const GLib.OptionEntry[] options = {
319     {"dbus-launched",0,GLib.OptionFlags.REVERSE,GLib.OptionArg.NONE,
320      ref explicitly_launched,"launch for dbus rpc use",null},
321     {"flat-file-store",0,0,GLib.OptionArg.NONE,
322      ref use_flat_file_store,"force use of flat file identity store (used by default only for headless operation)",null},
323     {null}
324 };
325
326
327 public static int main(string[] args){
328 #if IPC_MSRPC
329         bool headless = false;
330 #else
331         bool headless = GLib.Environment.get_variable("DISPLAY") == null;
332 #endif
333
334         if (headless) {
335             explicitly_launched = false;
336         } else {
337             try {
338                 if (!Gtk.init_with_args(ref args, _(""), options, null)) {
339                     stdout.printf(_("unable to initialize window\n"));
340                     return -1;
341                 }
342             } catch (GLib.Error e) {
343                 stdout.printf(_("error: %s\n"),e.message);
344                 stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
345                 return -1;
346             }
347         }
348
349 #if OS_WIN32
350         // Force specific theme settings on Windows without requiring a gtkrc file
351         Gtk.Settings settings = Gtk.Settings.get_default ();
352         settings.set_string_property ("gtk-theme-name", "ms-windows", "moonshot");
353         settings.set_long_property ("gtk-menu-images", 0, "moonshot");
354 #endif
355
356         Intl.bindtextdomain (Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
357         Intl.bind_textdomain_codeset (Config.GETTEXT_PACKAGE, "UTF-8");
358         Intl.textdomain (Config.GETTEXT_PACKAGE);
359        
360            
361         var app = new IdentityManagerApp(headless, use_flat_file_store);
362         app.explicitly_launched = explicitly_launched;
363         
364         if (app.explicitly_launched) {
365             app.show();
366         }
367
368         if (headless) {
369 #if !IPC_MSRPC
370             MainLoop loop = new MainLoop();
371             loop.run();
372 #endif
373         } else {
374             Gtk.main();
375         }
376
377         return 0;
378     }
379