-
Notifications
You must be signed in to change notification settings - Fork 2
/
rdc_ui.py
486 lines (383 loc) · 17.1 KB
/
rdc_ui.py
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
#!/usr/bin/env python
# coding=utf-8
# TODOs
# - Gray out connect button as long as IP field has no content
# Some future ideas
# - File locking so two sessions of the same user cannot interfere
# - Error if saving an already existing item (unique fields?)
# - Immediate error box if connecting to an empty string
# - Edit / Delete / New context menu in treeview
# - Accelerators to all text boxes (set_mnemonic_widget on labels)
# - Use autogenerated fields in model.py
import pygtk
pygtk.require('2.0')
import gtk
import gconf
import optparse
import logging
import os
from os import path
import model
from model import RdpSettingsReader, ListEntry, RdpSettingsWriter
import connection
import settings
running_configuration = {}
BUTTONS_HAVE_ICONS_GCONF_PATH = "/desktop/gnome/interface/buttons_have_icons"
logging.getLogger().setLevel(settings.LOG_LEVEL)
def enable_button_icons_hack():
"""A dirty function that modifies a GNOME setting so that rdc_ui would display well..
This feature can be disabled in settings.py
"""
gconf_client = gconf.client_get_default()
if not gconf_client.get_bool(BUTTONS_HAVE_ICONS_GCONF_PATH):
logging.info("Updating gconf key %s", BUTTONS_HAVE_ICONS_GCONF_PATH)
gconf_client.set_bool(BUTTONS_HAVE_ICONS_GCONF_PATH, True)
def parse_args(conf):
parser = optparse.OptionParser()
parser.add_option("-r", "--readonly", help="Read-only (hardened) mode", action="store_true", default=False)
(options, args) = parser.parse_args()
# Only updates 'conf' dict if user specified a change-of-settings (e.g. -r)
# Be careful not to set defaults here when user didn't pass params, so not to eclipse conf file settings when not needed
if options.readonly:
conf["readonly"] = "yes"
def populate_running_configuration():
"""Uses both config file and then cli args to populate the 'conf' dict
Returns the candidate running configuration dict"""
# DEFAULTS:
conf = {
"readonly": False,
}
model.load_general_settings_from_file(conf)
parse_args(conf)
logging.debug("Running configuration:\n%s", conf)
return conf
def generate_autodetected_dimentions():
screen = gtk.gdk.Screen()
(width, height) = (screen.get_width(), screen.get_height())
return (width, height)
class RdcUI(object):
"""Class responsible for the UI display and behavior"""
def on_connect_button_click(self, widget, data=None):
fields = {}
for field in model.ENTRY_FIELDS:
fields[field] = self.textboxes[field].get_text()
if (not fields["address"] or not fields["user"]):
msg_dialog = gtk.MessageDialog(self.window, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK,
message_format = "Please insert host and username")
msg_dialog.show_all()
msg_dialog.run()
msg_dialog.destroy()
return
# Dualmon and TLS handling below
pwd = None
should_dualmon = path.exists(path.expanduser('~/.fakexinerama'))
msg_dialog = gtk.MessageDialog(self.window, flags=0, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_OK,
message_format = "Please insert your password:")
action_area = msg_dialog.get_content_area()
pwd_entry = gtk.Entry()
pwd_entry.set_visibility(False)
action_area.pack_start(pwd_entry)
# Get the password
pwd_entry.connect('activate', lambda _:msg_dialog.response(gtk.RESPONSE_OK))
msg_dialog.set_default_response(gtk.RESPONSE_OK)
msg_dialog.show_all()
msg_dialog.run()
pwd = pwd_entry.get_text()
msg_dialog.destroy()
if (not pwd):
msg_dialog = gtk.MessageDialog(self.window, flags=0, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK,
message_format = "No password given")
msg_dialog.show_all()
msg_dialog.run()
msg_dialog.destroy()
return
logging.info("Connecting to %s (%s)", fields["address"], fields)
proc = ""
try:
proc = connection.rdp_connect(
address=fields["address"],
user=fields["user"],
domain=fields["domain"],
password=pwd,
dualmon=should_dualmon,
)
except connection.ConnectionFailedError:
logging.error("Connection failed")
messagebox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message_format="Failed connecting to '%s'" % (fields["address"]))
resp = messagebox.run()
messagebox.destroy()
logging.info("proc: %s", proc)
file = open("/opt/RDC/connections.log", "r+")
file.write(str(proc) + ":" + fields["address"] + "\n")
file.close()
return
def destroy(self, widget, data=None):
print "destroy signal occurred"
gtk.main_quit()
def create_buttons(self):
buttons = {}
connect_image = gtk.image_new_from_stock(gtk.STOCK_OK, size=gtk.ICON_SIZE_BUTTON)
buttons["connect"] = gtk.Button(label="_Connect")
buttons["connect"].set_image(connect_image)
buttons["connect"].set_flags(gtk.CAN_DEFAULT)
buttons["save"] = gtk.Button(u"← _Save")
buttons["edit"] = gtk.Button(u"→ _Edit")
buttons["new"] = gtk.Button(stock=gtk.STOCK_NEW)
buttons["delete"] = gtk.Button(stock=gtk.STOCK_DELETE)
buttons["exit"] = gtk.Button(u"Exit")
return buttons
def readonly_mode(self):
"""Grays-out widgets that shouldn't be reachable if readonly mode is desired"""
logging.info("Entering readonly mode")
widgets_to_disable = [
self.buttonbox,
self.form_table,
]
for widget in widgets_to_disable:
widget.set_sensitive(False)
def create_containers(self):
"""Creates the UI's skeleton
Creates and configures most of the containers (but not 'end' widgets such as buttons) for this UI"""
containers = {}
# HPaned: main_box
containers["main_box"] = gtk.HPaned()
# leftpane
containers["leftpane"] = gtk.ScrolledWindow()
containers["leftpane"].set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
containers["main_box"].pack1(containers["leftpane"], resize=True, shrink=True)
# rightpane
containers["rightpane"] = gtk.HBox(False, 10)
containers["main_box"].pack2(containers["rightpane"], resize=False, shrink=True)
# rightpane_align
containers["rightpane_align"] = gtk.Alignment()
containers["rightpane"].add(containers["rightpane_align"])
# rightpane_main_hbox
containers["rightpane_main_hbox"] = gtk.HBox(False, 0)
containers["rightpane_main_hbox"].set_spacing(10)
containers["rightpane_main_hbox"].set_border_width(10)
containers["rightpane_align"].add(containers["rightpane_main_hbox"])
# Vertical seperator
containers["rightpane_main_hbox"].pack_start(gtk.VSeparator(), False, False, 0)
# button_align
containers["button_align"] = gtk.Alignment()
containers["rightpane_main_hbox"].pack_start(containers["button_align"], False, False, 0)
# Vertical seperator
containers["rightpane_main_hbox"].pack_start(gtk.VSeparator(), False, False, 0)
# rightmost_vbox
containers["rightmost_vbox"] = gtk.VBox(False, 10)
containers["rightpane_main_hbox"].pack_start(containers["rightmost_vbox"], False, False, 0)
# connect_button_align
containers["connect_button_align"] = gtk.Alignment(0.5, 1, 1, 0)
containers["connect_button_align"].set_padding(25,0,0,0)
return containers
def create_buttonbox(self):
buttonbox = gtk.VButtonBox()
buttonbox.set_border_width(5)
buttonbox.set_spacing(5)
buttonbox.set_layout(gtk.BUTTONBOX_SPREAD)
buttonbox.add(self.buttons["edit"])
buttonbox.add(self.buttons["save"])
buttonbox.add(self.buttons["new"])
buttonbox.add(self.buttons["delete"])
buttonbox.add(self.buttons["exit"])
return buttonbox
def __init__(self):
"""This constructor is mainly responsible for creating the GUI"""
# Create the liststore
self.liststore = model.create_liststore()
self.liststore = model.populate(self.liststore)
# create a new window
self.window = self.create_window()
# Create buttons
self.buttons = self.create_buttons()
self.window.set_default(self.buttons["connect"])
# Create main containers
self.containers = self.create_containers()
self.window.add(self.containers["main_box"])
# Create the treeview
self.treeview = self.create_treeview(self.liststore)
self.containers["leftpane"].add(self.treeview)
# buttonbox
self.buttonbox = self.create_buttonbox()
self.containers["button_align"].add(self.buttonbox)
# TextEntries
self.textboxes = {}
for field in model.ENTRY_FIELDS:
self.textboxes[field] = gtk.Entry()
self.textboxes[field].set_activates_default(True)
self.form_table = self.create_form()
self.containers["rightmost_vbox"].pack_start(self.form_table, False, False, 0)
self.containers["rightmost_vbox"].pack_start(self.containers["connect_button_align"])
# Connect button
self.containers["connect_button_align"].add(self.buttons["connect"])
# and the window
self.window.show_all()
# Unselect the treeview
self.treeview.get_selection().unselect_all()
def create_form(self):
frame = gtk.Frame(label="Connection parameters")
table = gtk.Table(2, 2, False)
table.set_row_spacings(5)
table.set_col_spacings(10)
table.set_border_width(8)
count = 0
labels = []
for field in model.ENTRY_FIELDS:
desc = model.FIELD_DESCRIPTION[field]
if field in model.REQUIRED_FIELDS:
# Required field
label_desc = "*%s" % (desc)
else:
# Optional field
label_desc = " %s" % (desc)
labels.append(gtk.Label(label_desc))
labels[count].set_alignment(0, 0.5)
table.attach(labels[count], 0, 1, count+1, count+2)
table.attach(self.textboxes[field], 1, 2, count+1, count+2)
count += 1
frame.add(table)
return frame
def cell_edited(self, cell, path, new_text, user_data):
(liststore, column) = user_data
logging.info("Edited cell cell=%s, column=%s, path=%s, new_text=%s, updating and saving..", cell, column, path, new_text)
liststore[path][column] = new_text
self.save()
# TreeView
def create_treeview(self, liststore):
treeview = gtk.TreeView(liststore)
treeview.set_size_request(settings.LIST_WIDTH, 0)
treeview.set_grid_lines(True)
# Add columns and cells
treeview_columns = []
cells = []
count = 0
for field in model.ENTRY_FIELDS:
desc = model.FIELD_DESCRIPTION[field]
cells.append(gtk.CellRendererText())
treeview_columns.append(gtk.TreeViewColumn(desc, cells[count], text=count))
treeview_columns[count].set_resizable(True)
treeview_columns[count].set_sort_indicator(True)
treeview_columns[count].set_sort_column_id(count)
treeview.append_column(treeview_columns[count])
count += 1
treeview.columns_autosize()
return treeview
def update_form(self, list_entry):
"""Reads the contents of the provided list_entry and updates it in the form"""
for field in model.ENTRY_FIELDS:
list_entry_field = getattr(list_entry, field)
self.textboxes[field].set_text(list_entry_field)
return
def on_treeview_entry_select(self, treeview):
liststore, iter = treeview.get_selection().get_selected()
liststore = treeview.get_model()
list_entry = ListEntry.init_by_iter(iter, liststore)
self.update_form(list_entry)
return
def on_treeview_entry_doubleclick(self, treeview, path, column):
self.on_treeview_entry_select(treeview)
self.on_connect_button_click(treeview)
def on_save_button_click(self, widget, data=None):
fields = {}
for field in model.ENTRY_FIELDS:
fields[field] = self.textboxes[field].get_text()
if not fields["address"]:
messagebox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message_format="Save failed: required field is empty")
resp = messagebox.run()
messagebox.destroy()
return
print "Address:%s" % fields["address"]
list_entry = ListEntry(address=fields["address"],
name=fields["name"],
user=fields["user"],
domain=fields["domain"])
row = list_entry.to_liststore_row_format()
self.liststore.append(row)
logging.info("Adding a new entry")
self.save()
def on_del_button_click(self, widget, data=None):
liststore, iter = self.treeview.get_selection().get_selected()
if iter is None:
messagebox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message_format="Nothing is selected")
resp = messagebox.run()
messagebox.destroy()
return
messagebox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, message_format="Are you sure you want to delete this entry?")
resp = messagebox.run()
messagebox.destroy()
if resp == gtk.RESPONSE_NO:
# Cancel operation
return
self.liststore.remove(iter)
logging.info("Deleting entry")
self.save()
def save(self):
"""Save action - calls the model's save-to-file function"""
assert(running_configuration["readonly"] != "yes") # Extra safety
logging.info("Saving...")
model.dump_settings_to_file(self.liststore)
def on_new_button_click(self, widget, data=None):
self.update_form(ListEntry.init_empty())
self.textboxes["name"].grab_focus()
def on_edit_button_click(self, widget, data=None):
liststore, iter = self.treeview.get_selection().get_selected()
if iter is None:
messagebox = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
message_format="Nothing is selected")
resp = messagebox.run()
messagebox.destroy()
return
def on_exit_button_click(self, widget, data=None):
exit();
# Populate form
list_entry = ListEntry.init_by_iter(iter, liststore)
self.update_form(list_entry)
# Remove from liststore
self.liststore.remove(iter)
logging.info("Deleting entry (edit mode)")
self.save()
self.textboxes["name"].grab_focus()
def register_events(self):
# Window: delete (close)
self.window.connect("delete-event", gtk.main_quit)
# Connect button
self.buttons["connect"].connect("clicked", self.on_connect_button_click, None)
# Treeview
# single click
self.treeview.connect("cursor-changed", self.on_treeview_entry_select)
# double click
self.treeview.connect("row-activated", self.on_treeview_entry_doubleclick)
# Save button
self.buttons["save"].connect("clicked", self.on_save_button_click)
# Del button
self.buttons["delete"].connect("clicked", self.on_del_button_click)
# New button
self.buttons["new"].connect("clicked", self.on_new_button_click)
# Edit button
self.buttons["edit"].connect("clicked", self.on_edit_button_click)
# Exit button
self.buttons["exit"].connect("clicked", self.on_exit_button_click)
def create_window(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
if settings.DISABLE_CLOSE_BUTTON:
window.set_deletable(False)
# Sets the border width of the window.
window.set_border_width(10)
window.set_title(settings.WINDOW_TITLE)
window.set_default_size(settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT)
window.set_resizable(True)
window.set_position(gtk.WIN_POS_CENTER)
return window
def main(self):
global running_configuration
running_configuration = populate_running_configuration()
if settings.ENABLE_BUTTONS_HAVE_ICONS:
enable_button_icons_hack()
self.register_events()
self.textboxes["name"].grab_focus()
if running_configuration["readonly"] == "yes":
self.readonly_mode()
gtk.main()
if __name__ == "__main__":
rdcui = RdcUI()
rdcui.main()