/
gui.py
341 lines (291 loc) · 12.1 KB
/
gui.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
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# PyRoom - A clone of WriteRoom
# Copyright (c) 2007 Nicolas P. Rougier & NoWhereMan
# Copyright (c) 2008 The Pyroom Team - See AUTHORS file for more information
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
"""
basic global GUI
Additionally allows user to apply custom settings
"""
import gtk
import gobject
import pango
import gtk.glade
import ConfigParser
import os
from sys import platform
if platform == 'win32':
data_home = os.environ['APPDATA']
else:
from xdg.BaseDirectory import xdg_data_home as data_home
from pyroom_error import PyroomError
from globals import state, config
ORIENTATION = {
'top':0,
'center':0.5,
'bottom':1,
}
def calculate_real_tab_width(textview, tab_size):
"""calculate the width of `tab_size` spaces in the current font"""
tab_string = tab_size * '0'
layout = pango.Layout(textview.get_pango_context())
layout.set_text(tab_string)
return layout.get_size()[0]
class Theme(dict):
"""basically a dict with some utility methods"""
def __init__(self, theme_name):
dict.__init__(self)
theme_filename = self._lookup_theme(theme_name)
if not theme_filename:
raise PyroomError(_('theme not found: %s') % theme_name)
theme_file = ConfigParser.SafeConfigParser()
theme_file.read(theme_filename)
self.update(theme_file.items('theme'))
def __getitem__(self, item):
"""get default values from our default theme
this is to handle custom themes from older versions"""
try:
return dict.__getitem__(self, item)
except KeyError:
default_theme = Theme('green')
return default_theme[item]
def _lookup_theme(self, theme_name):
"""lookup theme_filename for given theme_name
order of preference is homedir, global dir, source dir (if available)"""
local_directory = os.path.join(data_home, 'pyroom', 'themes')
global_directory = '/usr/share/pyroom/themes' # FIXME: platform
# in case PyRoom is run without installation
fallback_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'..',
'themes'
)
for dirname in (local_directory, global_directory, fallback_directory):
filename = os.path.join(dirname, theme_name + '.theme')
if os.path.isfile(filename):
return filename
def save(self, filename):
"""save a theme"""
theme_file = ConfigParser.SafeConfigParser()
theme_file.add_section('theme')
for key, value in self.iteritems():
theme_file.set('theme', key, str(value))
theme_file.set('theme', 'name', os.path.basename(filename))
theme_file.write(open(filename + '.theme', 'w'))
class FadeLabel(gtk.Label):
""" GTK Label with timed fade out effect """
active_duration = 3000 # Fade start after this time
fade_duration = 1500.0 # Fade duration
def __init__(self, message='', active_color=None, inactive_color=None):
gtk.Label.__init__(self, message)
if not active_color:
active_color = '#ffffff'
self.active_color = active_color
if not inactive_color:
inactive_color = '#000000'
self.fade_level = 0
self.inactive_color = inactive_color
self.idle = 0
def set_text(self, message, duration=None):
"""change text that is displayed
@param message: message to display
@param duration: duration in miliseconds"""
if not duration:
duration = self.active_duration
self.modify_fg(gtk.STATE_NORMAL,
gtk.gdk.color_parse(self.active_color))
gtk.Label.set_text(self, message)
if self.idle:
gobject.source_remove(self.idle)
self.idle = gobject.timeout_add(duration, self.fade_start)
def fade_start(self):
"""start fading timer"""
self.fade_level = 1.0
if self.idle:
gobject.source_remove(self.idle)
self.idle = gobject.timeout_add(25, self.fade_out)
def fade_out(self):
"""now fade out"""
color = gtk.gdk.color_parse(self.inactive_color)
(red1, green1, blue1) = (color.red, color.green, color.blue)
color = gtk.gdk.color_parse(self.active_color)
(red2, green2, blue2) = (color.red, color.green, color.blue)
red = red1 + int(self.fade_level * (red2 - red1))
green = green1 + int(self.fade_level * (green2 - green1))
blue = blue1 + int(self.fade_level * (blue2 - blue1))
self.modify_fg(gtk.STATE_NORMAL, gtk.gdk.Color(red, green, blue))
self.fade_level -= 1.0 / (self.fade_duration / 25)
if self.fade_level > 0:
return True
self.idle = 0
return False
class GUI(object):
"""our basic global gui object"""
def __init__(self):
# Theme
theme_name = config.get('visual', 'theme')
self.theme = Theme(theme_name)
self.status = FadeLabel()
# Main window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_name('PyRoom')
self.window.set_title("PyRoom")
self.window.connect('delete_event', self.delete_event)
self.window.connect('destroy', self.destroy)
self.textbox = gtk.TextView()
self.textbox.connect('scroll-event', self.scroll_event)
self.textbox.set_wrap_mode(gtk.WRAP_WORD)
self.fixed = gtk.Fixed()
self.vbox = gtk.VBox()
self.align = gtk.Alignment()
self.align.add(self.vbox)
self.window.add(self.align)
self.boxout = gtk.EventBox()
self.boxout.set_border_width(1)
self.boxin = gtk.EventBox()
self.boxin.set_border_width(1)
self.vbox.pack_start(self.boxout, True, True, 1)
self.boxout.add(self.boxin)
self.scrolled = gtk.ScrolledWindow()
self.boxin.add(self.scrolled)
self.scrolled.add(self.textbox)
self.scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_NEVER)
self.scrolled.show()
self.scrolled.set_property('resize-mode', gtk.RESIZE_PARENT)
self.textbox.set_property('resize-mode', gtk.RESIZE_PARENT)
self.vbox.set_property('resize-mode', gtk.RESIZE_PARENT)
self.vbox.show_all()
# Status
self.hbox = gtk.HBox()
self.hbox.set_spacing(12)
self.hbox.pack_end(self.status, True, True, 0)
self.vbox.pack_end(self.hbox, False, False, 0)
self.status.set_alignment(0.0, 0.5)
self.status.set_justify(gtk.JUSTIFY_LEFT)
self.apply_theme()
def apply_theme(self):
"""immediately apply the theme given in configuration
this has changed from previous versions! Takes no arguments!
Only uses configuration!"""
# text cursor
gtkrc_string = """\
style "pyroom-colored-cursor" {
GtkTextView::cursor-color = '%s'
bg_pixmap[NORMAL] = "<none>"
}
class "GtkWidget" style "pyroom-colored-cursor"
""" % self.theme['foreground']
gtk.rc_parse_string(gtkrc_string)
padding = int(self.theme['padding'])
self.textbox.set_border_width(padding)
# Screen geometry
screen = gtk.gdk.screen_get_default()
root_window = screen.get_root_window()
mouse_x, mouse_y, mouse_mods = root_window.get_pointer()
current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y)
monitor_geometry = screen.get_monitor_geometry(current_monitor_number)
(screen_width, screen_height) = (monitor_geometry.width,
monitor_geometry.height)
width_percentage = float(self.theme['width'])
height_percentage = float(self.theme['height'])
# Sizing
self.vbox.set_size_request(
int(width_percentage * screen_width),
int(height_percentage * screen_height)
)
parse_color = lambda x: gtk.gdk.color_parse(self.theme[x])
# Colors
self.window.modify_bg(gtk.STATE_NORMAL, parse_color('background'))
self.boxout.modify_bg(gtk.STATE_NORMAL, parse_color('border'))
self.status.active_color = self.theme['foreground']
self.status.inactive_color = self.theme['background']
self.textbox.modify_bg(gtk.STATE_NORMAL, parse_color('textboxbg'))
self.textbox.modify_base(gtk.STATE_NORMAL, parse_color('textboxbg'))
self.textbox.modify_base(gtk.STATE_SELECTED, parse_color('foreground'))
self.textbox.modify_text(gtk.STATE_NORMAL, parse_color('foreground'))
self.textbox.modify_text(gtk.STATE_SELECTED, parse_color('textboxbg'))
self.textbox.modify_fg(gtk.STATE_NORMAL, parse_color('foreground'))
# Border
if not int(config.get('visual', 'showborder')):
self.boxin.set_border_width(0)
self.boxout.set_border_width(0)
else:
self.boxin.set_border_width(1)
self.boxout.set_border_width(1)
# Fonts
if config.get('visual', 'use_font_type') == 'custom' or\
not state['gnome_fonts']:
new_font = config.get('visual', 'custom_font')
else:
font_type = config.get('visual', 'use_font_type')
new_font = state['gnome_fonts'][font_type]
self.textbox.modify_font(pango.FontDescription(new_font))
tab_width = pango.TabArray(1, False)
tab_width.set_tab(0, pango.TAB_LEFT,
calculate_real_tab_width(self.textbox, 4)
)
self.textbox.set_tabs(tab_width)
# Indent
if config.get('visual', 'indent') == '1':
pango_context = self.textbox.get_pango_context()
current_font_size = pango_context.\
get_font_description().\
get_size() / 1024
self.textbox.set_indent(current_font_size * 2)
else:
self.textbox.set_indent(0)
# linespacing
linespacing = config.getint('visual', 'linespacing')
self.textbox.set_pixels_below_lines(linespacing)
self.textbox.set_pixels_above_lines(linespacing)
self.textbox.set_pixels_inside_wrap(linespacing)
# alignment
self.align.set(
xalign=0.5,
yalign=ORIENTATION[config.get('visual', 'alignment')],
xscale=0,
yscale=0
)
def quit(self):
""" quit pyroom """
gtk.main_quit()
def delete_event(self, widget, event, data=None):
""" Quit """
state['edit_instance'].dialog_quit()
return True
def destroy(self, widget, data=None):
""" Quit """
gtk.main_quit()
def scroll_event(self, widget, event):
""" Scroll event dispatcher """
if event.direction == gtk.gdk.SCROLL_UP:
self.scroll_up()
elif event.direction == gtk.gdk.SCROLL_DOWN:
self.scroll_down()
def scroll_down(self):
""" Scroll window down """
adj = self.scrolled.get_vadjustment()
if adj.upper > adj.page_size:
adj.value = min(adj.upper - adj.page_size, adj.value
+ adj.step_increment)
def scroll_up(self):
""" Scroll window up """
adj = self.scrolled.get_vadjustment()
if adj.value > adj.step_increment:
adj.value -= adj.step_increment
else:
adj.value = 0