forked from coyim/coyim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.go
585 lines (466 loc) · 13.7 KB
/
ui.go
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package gui
import (
"errors"
"fmt"
"log"
"os"
"runtime"
"github.com/twstrike/coyim/Godeps/_workspace/src/github.com/twstrike/gotk3adapter/gdki"
"github.com/twstrike/coyim/Godeps/_workspace/src/github.com/twstrike/gotk3adapter/glibi"
"github.com/twstrike/coyim/Godeps/_workspace/src/github.com/twstrike/gotk3adapter/gtki"
"github.com/twstrike/coyim/Godeps/_workspace/src/github.com/twstrike/gotk3adapter/pangoi"
"github.com/twstrike/coyim/config"
"github.com/twstrike/coyim/i18n"
rosters "github.com/twstrike/coyim/roster"
sessions "github.com/twstrike/coyim/session/access"
"github.com/twstrike/coyim/xmpp/interfaces"
)
const (
programName = "CoyIM"
applicationID = "im.coy.CoyIM"
localizationDomain = "coy"
)
type gtkUI struct {
roster *roster
app gtki.Application
window gtki.ApplicationWindow
accountsMenu gtki.MenuItem
notificationArea gtki.Box
viewMenu *viewMenu
optionsMenu *optionsMenu
unified *unifiedLayout
config *config.ApplicationConfig
*accountManager
displaySettings *displaySettings
keySupplier config.KeySupplier
tags *tags
toggleConnectAllAutomaticallyRequest chan bool
setShowAdvancedSettingsRequest chan bool
commands chan interface{}
sessionFactory sessions.Factory
dialerFactory interfaces.DialerFactory
}
// Graphics represent the graphic configuration
type Graphics struct {
gtk gtki.Gtk
glib glibi.Glib
gdk gdki.Gdk
pango pangoi.Pango
}
// CreateGraphics creates a Graphic represention from the given arguments
func CreateGraphics(gtkVal gtki.Gtk, glibVal glibi.Glib, gdkVal gdki.Gdk, pangoVal pangoi.Pango) Graphics {
return Graphics{
gtk: gtkVal,
glib: glibVal,
gdk: gdkVal,
pango: pangoVal,
}
}
var g Graphics
var coyimVersion string
// UI is the user interface functionality exposed to main
type UI interface {
Loop()
}
func argsWithApplicationName() *[]string {
newSlice := make([]string, len(os.Args))
copy(newSlice, os.Args)
newSlice[0] = programName
return &newSlice
}
// NewGTK returns a new client for a GTK ui
func NewGTK(version string, sf sessions.Factory, df interfaces.DialerFactory, gx Graphics) UI {
runtime.LockOSThread()
coyimVersion = version
g = gx
initSignals()
//*.mo files should be in ./i18n/locale_code.utf8/LC_MESSAGES/
g.glib.InitI18n(localizationDomain, "./i18n")
g.gtk.Init(argsWithApplicationName())
ret := >kUI{
commands: make(chan interface{}, 5),
toggleConnectAllAutomaticallyRequest: make(chan bool, 100),
setShowAdvancedSettingsRequest: make(chan bool, 100),
dialerFactory: df,
}
var err error
flags := glibi.APPLICATION_FLAGS_NONE
if *config.MultiFlag {
flags = glibi.APPLICATION_NON_UNIQUE
}
ret.app, err = g.gtk.ApplicationNew(applicationID, flags)
if err != nil {
panic(err)
}
ret.keySupplier = config.CachingKeySupplier(ret.getMasterPassword)
ret.accountManager = newAccountManager(ret)
ret.sessionFactory = sf
return ret
}
func (u *gtkUI) confirmAccountRemoval(acc *config.Account, removeAccountFunc func(*config.Account)) {
builder := builderForDefinition("ConfirmAccountRemoval")
obj, _ := builder.GetObject("RemoveAccount")
dialog := obj.(gtki.MessageDialog)
dialog.SetTransientFor(u.window)
dialog.SetProperty("text", acc.Account)
response := dialog.Run()
if gtki.ResponseType(response) == gtki.RESPONSE_YES {
removeAccountFunc(acc)
}
dialog.Destroy()
}
func (u *gtkUI) initialSetupWindow() {
u.wouldYouLikeToEncryptYourFile(func(res bool) {
u.config.SetShouldSaveFileEncrypted(res)
k := func() {
go u.showFirstAccountWindow()
}
if res {
u.captureInitialMasterPassword(k)
} else {
k()
}
})
}
func (u *gtkUI) loadConfig(configFile string) {
u.config.WhenLoaded(func(c *config.ApplicationConfig) {
u.configLoaded(c)
})
ok := false
var conf *config.ApplicationConfig
var err error
for !ok {
conf, ok, err = config.LoadOrCreate(configFile, u.keySupplier)
if !ok {
log.Printf("couldn't open encrypted file - either the user didn't supply a password, or the password was incorrect: %v", err)
u.keySupplier.Invalidate()
u.keySupplier.LastAttemptFailed()
}
}
// We assign config here, AFTER the return - so that a nil config means we are in a state of incorrectness and shouldn't do stuff.
// We never check, since a panic here is a serious programming error
u.config = conf
if err != nil {
log.Printf(err.Error())
doInUIThread(u.initialSetupWindow)
return
}
if u.config.UpdateToLatestVersion() {
u.saveConfigOnlyInternal()
}
}
func (u *gtkUI) configLoaded(c *config.ApplicationConfig) {
u.buildAccounts(c, u.sessionFactory, u.dialerFactory)
doInUIThread(func() {
if u.viewMenu != nil {
u.viewMenu.setFromConfig(c)
}
if u.optionsMenu != nil {
u.optionsMenu.setFromConfig(c)
}
if u.window != nil {
u.window.Emit(accountChangedSignal.String())
}
})
u.addInitialAccountsToRoster()
if c.ConnectAutomatically {
u.connectAllAutomatics(false)
}
go u.listenToToggleConnectAllAutomatically()
go u.listenToSetShowAdvancedSettings()
}
func (u *gtkUI) saveConfigInternal() error {
err := u.saveConfigOnlyInternal()
if err != nil {
return err
}
u.addNewAccountsFromConfig(u.config, u.sessionFactory, u.dialerFactory)
if u.window != nil {
u.window.Emit(accountChangedSignal.String())
}
return nil
}
func (u *gtkUI) saveConfigOnlyInternal() error {
return u.config.Save(u.keySupplier)
}
func (u *gtkUI) SaveConfig() {
go func() {
err := u.saveConfigInternal()
if err != nil {
log.Println("Failed to save config file:", err.Error())
}
}()
}
func (u *gtkUI) removeSaveReload(acc *config.Account) {
//TODO: the account configs should be managed by the account manager
u.accountManager.removeAccount(acc, func() {
u.config.Remove(acc)
u.SaveConfig()
})
}
func (u *gtkUI) saveConfigOnly() {
go func() {
err := u.saveConfigOnlyInternal()
if err != nil {
log.Println("Failed to save config file:", err.Error())
}
}()
}
func (u *gtkUI) Loop() {
u.app.Connect("activate", func() {
activeWindow := u.app.GetActiveWindow()
if activeWindow == nil {
go u.watchCommands()
go u.observeAccountEvents()
applyHacks()
u.mainWindow()
go u.loadConfig(*config.ConfigFile)
} else {
activeWindow.Present()
}
})
u.app.Run([]string{})
}
func (u *gtkUI) initRoster() {
u.roster = u.newRoster()
}
func (u *gtkUI) mainWindow() {
builder := newBuilder("Main")
builder.ConnectSignals(map[string]interface{}{
"on_close_window_signal": u.quit,
"on_add_contact_window_signal": u.addContactWindow,
"on_about_dialog_signal": u.aboutDialog,
"on_feedback_dialog_signal": u.feedbackDialog,
"on_toggled_check_Item_Merge_signal": u.toggleMergeAccounts,
"on_toggled_check_Item_Show_Offline_signal": u.toggleShowOffline,
"on_toggled_encrypt_configuration_file_signal": u.toggleEncryptedConfig,
})
win, err := builder.GetObject("mainWindow")
if err != nil {
panic(err)
}
u.window = win.(gtki.ApplicationWindow)
u.window.SetApplication(u.app)
u.displaySettings = detectCurrentDisplaySettingsFrom(u.window)
// This must happen after u.displaySettings is initialized
// So now, roster depends on displaySettings which depends on mainWindow
u.initRoster()
g.gtk.LabelNew("hello")
// AccountsMenu
u.accountsMenu = builder.getObj("AccountsMenu").(gtki.MenuItem)
// ViewMenu
u.viewMenu = new(viewMenu)
u.viewMenu.merge = builder.getObj("CheckItemMerge").(gtki.CheckMenuItem)
u.displaySettings.defaultSettingsOn(u.viewMenu.merge)
u.viewMenu.offline = builder.getObj("CheckItemShowOffline").(gtki.CheckMenuItem)
u.displaySettings.defaultSettingsOn(u.viewMenu.offline)
// OptionsMenu
u.optionsMenu = new(optionsMenu)
u.optionsMenu.encryptConfig = builder.getObj("EncryptConfigurationFileCheckMenuItem").(gtki.CheckMenuItem)
u.displaySettings.defaultSettingsOn(u.optionsMenu.encryptConfig)
u.initMenuBar()
obj, _ := builder.GetObject("Vbox")
vbox := obj.(gtki.Box)
vbox.PackStart(u.roster.widget, true, true, 0)
if *config.SingleWindowFlag {
obj, _ := builder.GetObject("Hbox")
hbox := obj.(gtki.Box)
u.unified = newUnifiedLayout(u, vbox, hbox)
}
u.notificationArea = builder.getObj("notification-area").(gtki.Box)
u.config.WhenLoaded(func(a *config.ApplicationConfig) {
if a.Display.HideFeedbackBar {
return
}
doInUIThread(u.addFeedbackInfoBar)
})
u.connectShortcutsMainWindow(u.window)
u.window.SetIcon(coyimIcon.getPixbuf())
g.gtk.WindowSetDefaultIcon(coyimIcon.getPixbuf())
u.window.ShowAll()
}
func (u *gtkUI) addInitialAccountsToRoster() {
for _, account := range u.accounts {
u.roster.update(account, rosters.New())
}
}
func (u *gtkUI) addFeedbackInfoBar() {
builder := builderForDefinition("FeedbackInfo")
obj, _ := builder.GetObject("feedbackInfo")
infobar := obj.(gtki.InfoBar)
u.notificationArea.PackEnd(infobar, true, true, 0)
infobar.ShowAll()
builder.ConnectSignals(map[string]interface{}{
"handleResponse": func(info gtki.InfoBar, response gtki.ResponseType) {
if response != gtki.RESPONSE_CLOSE {
return
}
infobar.Hide()
infobar.Destroy()
u.config.Display.HideFeedbackBar = true
u.saveConfigOnly()
},
})
obj, _ = builder.GetObject("feedbackButton")
button := obj.(gtki.Button)
button.Connect("clicked", func() {
doInUIThread(u.feedbackDialog)
})
}
func (u *gtkUI) quit() {
u.accountManager.disconnectAll()
u.app.Quit()
}
func (u *gtkUI) askForPassword(accountName string, cancel func(), connect func(string) error) {
dialogTemplate := "AskForPassword"
builder := builderForDefinition(dialogTemplate)
obj, _ := builder.GetObject(dialogTemplate)
dialog := obj.(gtki.Dialog)
obj, _ = builder.GetObject("accountName")
label := obj.(gtki.Label)
label.SetText(accountName)
label.SetSelectable(true)
builder.ConnectSignals(map[string]interface{}{
"on_entered_password_signal": func() {
passwordObj, _ := builder.GetObject("password")
passwordEntry := passwordObj.(gtki.Entry)
password, _ := passwordEntry.GetText()
if len(password) > 0 {
go connect(password)
dialog.Destroy()
}
},
"on_cancel_password_signal": func() {
cancel()
dialog.Destroy()
},
})
dialog.SetTransientFor(u.window)
dialog.ShowAll()
}
func (u *gtkUI) feedbackDialog() {
builder := builderForDefinition("Feedback")
obj, _ := builder.GetObject("dialog")
dialog := obj.(gtki.MessageDialog)
dialog.SetTransientFor(u.window)
dialog.Run()
dialog.Destroy()
}
func (u *gtkUI) shouldViewAccounts() bool {
return !u.config.Display.MergeAccounts
}
func authors() []string {
return []string{
"Fan Jiang - fan.torchz@gmail.com",
"Iván Pazmiño - iapazmino@gmail.com",
"Ola Bini - ola@olabini.se",
"Reinaldo de Souza Jr - juniorz@gmail.com",
"Tania Silva - tsilva@thoughtworks.com",
"Adam Langley",
"Gray Leonard - gl7039a@american.edu",
"Bruce Leidl - bruce@subgraph.com",
"xSmurf - matth@subgraph.com",
}
}
func (u *gtkUI) aboutDialog() {
dialog, _ := g.gtk.AboutDialogNew()
dialog.SetName(i18n.Local("Coy IM!"))
dialog.SetProgramName(programName)
dialog.SetAuthors(authors())
dialog.SetVersion(coyimVersion)
dialog.SetLicense(`GNU GENERAL PUBLIC LICENSE, Version 3`)
dialog.SetWrapLicense(true)
dialog.SetTransientFor(u.window)
dialog.Run()
dialog.Destroy()
}
func (u *gtkUI) addContactWindow() {
accounts := make([]*account, 0, len(u.accounts))
for i := range u.accounts {
acc := u.accounts[i]
if acc.connected() {
accounts = append(accounts, acc)
}
}
dialog := presenceSubscriptionDialog(accounts, func(accountID, peer, msg, nick string, autoAuth bool) error {
account, ok := u.roster.getAccount(accountID)
if !ok {
return fmt.Errorf(i18n.Local("There is no account with the id %q"), accountID)
}
if !account.connected() {
return errors.New(i18n.Local("Can't send a contact request from an offline account"))
}
err := account.session.RequestPresenceSubscription(peer, msg)
if nick != "" {
account.session.GetConfig().SavePeerDetails(peer, nick, []string{})
u.SaveConfig()
}
if autoAuth {
account.session.AutoApprove(peer)
}
return err
})
dialog.SetTransientFor(u.window)
dialog.ShowAll()
}
func (u *gtkUI) listenToToggleConnectAllAutomatically() {
for {
val := <-u.toggleConnectAllAutomaticallyRequest
u.config.ConnectAutomatically = val
u.saveConfigOnly()
}
}
func (u *gtkUI) setConnectAllAutomatically(val bool) {
u.toggleConnectAllAutomaticallyRequest <- val
}
func (u *gtkUI) setShowAdvancedSettings(val bool) {
u.setShowAdvancedSettingsRequest <- val
}
func (u *gtkUI) listenToSetShowAdvancedSettings() {
for {
val := <-u.setShowAdvancedSettingsRequest
u.config.AdvancedOptions = val
u.saveConfigOnly()
}
}
func (u *gtkUI) initMenuBar() {
u.window.Connect(accountChangedSignal.String(), func() {
doInUIThread(func() {
u.buildAccountsMenu()
u.accountsMenu.ShowAll()
u.rosterUpdated()
})
})
u.buildAccountsMenu()
u.accountsMenu.ShowAll()
}
func (u *gtkUI) rosterUpdated() {
doInUIThread(u.roster.redraw)
if u.unified != nil {
doInUIThread(u.unified.update)
}
}
func (u *gtkUI) connectionInfo(account *account) {
u.connectionInfoDialog(account)
}
func (u *gtkUI) editAccount(account *account) {
u.accountDialog(account.session, account.session.GetConfig(), func() {
u.SaveConfig()
account.session.ReloadKeys()
})
}
func (u *gtkUI) removeAccount(account *account) {
u.confirmAccountRemoval(account.session.GetConfig(), func(c *config.Account) {
account.session.SetWantToBeOnline(false)
account.disconnect()
u.removeSaveReload(c)
})
}
func (u *gtkUI) toggleAutoConnectAccount(account *account) {
account.session.GetConfig().ToggleConnectAutomatically()
u.saveConfigOnly()
}
func (u *gtkUI) toggleAlwaysEncryptAccount(account *account) {
account.session.GetConfig().ToggleAlwaysEncrypt()
u.saveConfigOnly()
}