Source

noor / noorgtk.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
487
488
489
490
491
492
493
494
495
496
#!/usr/bin/env python
import subprocess
import sys

import gtk
import pango

import noor.uihelpers
import noor.i18n
from noor import uihelpers


class AyaCollector(object):

    def __init__(self, text_view, config):
        self.view = text_view
        self.buffer = text_view.get_buffer()
        self.result = []
        self._create_tags(config)
        self.view.set_editable(False)
        self.view.set_cursor_visible(False)
        self.view.set_wrap_mode(gtk.WRAP_WORD)
        self.number = 0
        self.juz_number = 0
        self.sajda_number = 0

    def _create_tags(self, config):
        fgcolor = uihelpers.get_option(config, 'gtk.fgcolor')
        bgcolor = uihelpers.get_option(config, 'gtk.bgcolor')
        dirs = {'rtl': gtk.TEXT_DIR_RTL, 'ltr': gtk.TEXT_DIR_LTR}
        font = uihelpers.get_option(config, 'gtk.font', '')
        trans_font = uihelpers.get_option(config, 'gtk.translation_font', '')
        attrs = {'direction': dirs['rtl']}
        if fgcolor:
            attrs['foreground'] = fgcolor
        if bgcolor:
            attrs['background'] = bgcolor
        attrs1 = dict(attrs)
        attrs1.update(self._font_attrs(font))
        attrs2 = dict(attrs)
        attrs3 = dict(attrs1)
        attrs4 = dict(attrs1)
        attrs5 = dict(attrs1)
        attrs2.update(self._font_attrs(trans_font))
        attrs2['direction'] = direction=dirs[self._get_trans_dir(config)]
        attrs3['background'] = 'green'
        attrs4['foreground'] = 'blue'
        attrs5['foreground'] = 'red'
        self.tag1 = self.buffer.create_tag('quran', **attrs1)
        self.tag2 = self.buffer.create_tag('trans', **attrs2)
        self.tag3 = self.buffer.create_tag('juz', **attrs3)
        self.tag4 = self.buffer.create_tag('sign', **attrs4)
        self.tag5 = self.buffer.create_tag('sajda', **attrs5)

    def _font_attrs(self, rawfont):
        font = uihelpers.parse_font(rawfont)
        attrs = {}
        if font.face is not None:
            attrs['font'] = font.face
        if font.size is not None:
            attrs['size-points'] = int(font.size)
        if font.fgcolor is not None:
            attrs['foreground'] = font.fgcolor
        if font.bgcolor is not None:
            attrs['background'] = font.bgcolor
        return attrs

    def _get_trans_dir(self, config):
        trans_path = uihelpers.get_translation_path(config)
        if trans_path is not None:
            trans_info = uihelpers._zekr_translation_info(trans_path)
        else:
            trans_info = {}
        return trans_info.get('direction', 'rtl')

    def __call__(self, text, number=None, sajda=None,
                 translation=None, juz_start=None):
        if juz_start is not None:
            self._insert(juz_start.ljust(2), self.tag3)
            self._insert('\n')
        self._set_aya_mark(number)
        self._insert(text, self.tag1)
        # handling aya sign
        if number is not None:
            sign = str(number)
            sign_tag = self.tag4
            if sajda == 'minor':
                sign = '*%s*' % sign
            elif sajda == 'major':
                sign = '**%s**' % sign
            if sajda is not None:
                sign_tag = self.tag5
            self._insert('[', self.tag4)
            self._insert('%s' % sign, sign_tag)
            self._insert(']\n', self.tag4)
        else:
            self._insert('\n')
        if translation is not None:
            self._insert(translation + '\n', self.tag2)
        self._insert('\n')

    def _set_aya_mark(self, number):
        if number:
            self.number += 1
            self._set_mark(str(self.number))

    def _set_mark(self, name):
        textiter = self.buffer.get_iter_at_mark(self.buffer.get_insert())
        mark = self.buffer.create_mark(name, textiter, left_gravity=True)

    def _insert(self, text, *tags):
        self.buffer.insert_with_tags(self.buffer.get_end_iter(),
                                     text, *tags)

    @property
    def text(self):
        return ''.join(self.result)


def prefixed(name):
    def decorator(func):
        def newfunc(self, *args, **kwds):
            try:
                if self.number is not None:
                    return func(self, self.number)
                else:
                    return func(self, _ask_number(self.config, _(name)))
            finally:
                self.number = None
        return newfunc
    return decorator


class NoorWindow(object):

    def __init__(self, config, quran, sura=None):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.config = config
        self.quran = quran
        self.trans = uihelpers.get_translation(config)
        self.window.set_border_width(1)
        self.window.set_size_request(800, 600)
        self.window.connect('destroy', self._quit)

        self.text_view = gtk.TextView()
        self.current_sura = None
        self.current_aya = 0
        self.number = None
        self.show_sura()

        self.sura_window = gtk.ScrolledWindow()
        self.sura_window.add(self.text_view)
        self.sura_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
        self.text_view.connect('key_press_event', self._key_pressed)
        self.window.add(self.sura_window)
        self.adjustment = self.sura_window.get_vscrollbar().get_adjustment()
        self.text_view.grab_focus()

    def show_sura(self, sura=None):
        if sura is not None and 0 < sura <= 114:
            self._clear_all()
            self.current_sura = sura
            self.current_aya = 0
            self._set_title(sura)
            collector = AyaCollector(self.text_view, self.config)
            uihelpers.write_sura(self.quran, self.config, sura,
                                 collector, self.trans)
            self._run_hook('gtk.sura_hook', [str(self.current_sura)])
        if self.current_sura is None:
            self._show_home()

    def _clear_all(self):
        self._set_title()
        self.text_view.get_buffer().set_text('')
        self.text_view.set_buffer(gtk.TextBuffer())

    def _show_home(self):
        self.current_sura = None
        self._clear_all()
        _insert_home(self.text_view)

    def _set_title(self, sura=None):
        title = 'Noor'
        if sura is not None:
            title += ' - ' + str(sura) + '. ' + self.quran.suras[sura - 1].name
        else:
            title += ' - About'
        self.window.set_title(title)

    def _key_pressed(self, widget, event, data=None):
        if event.type == gtk.gdk.KEY_PRESS:
            keyval = event.keyval
            keys = None
            grab = False
            if (event.state & gtk.gdk.CONTROL_MASK and
                event.state & gtk.gdk.MOD1_MASK):
                keys = self.cm_keys
            elif event.state & gtk.gdk.CONTROL_MASK:
                keys = self.c_keys
            elif event.state & gtk.gdk.MOD1_MASK:
                keys = self.m_keys
            elif event.state & gtk.gdk.SHIFT_MASK:
                keys = self.s_keys
                grab = True
            else:
                keys = self.keys
                grab = True
            if keyval in keys:
                keys[keyval](self)
                grab = True
            if ord('0') <= keyval <= ord('9'):
                if self.number is None:
                    self.number = 0
                self.number = self.number * 10 + (keyval - ord('0'))
            return grab

    @prefixed(_('sura'))
    def _goto_sura(self, number):
        self.show_sura(number)

    @prefixed(_('juz'))
    def _goto_juz(self, juz):
        if 0 < juz <= 30:
            sura, aya = self.quran.juz_starts[juz - 1]
            if self.current_sura != sura:
                self.show_sura(sura)
            self._goto_mark(str(aya), location=0.1)

    def _ask_sura(self):
        sura = _ask_sura(self.config, self.quran)
        self.show_sura(sura)

    def _adjust_page(self, increment):
        new_value = self.adjustment.value + increment
        newvalue = max(self.adjustment.lower,
                       min(new_value, self.adjustment.upper
                           - self.adjustment.page_size))
        self.adjustment.set_value(newvalue)

    def _prev_line(self):
        self._adjust_page(-self.adjustment.step_increment)

    def _next_line(self):
        self._adjust_page(self.adjustment.step_increment)

    def _prev_page(self):
        self._adjust_page(-self.adjustment.page_increment)

    def _next_page(self):
        self._adjust_page(self.adjustment.page_increment)

    def _prev_sura(self):
        if self.current_sura is not None:
            self.show_sura(self.current_sura - 1)

    def _next_sura(self):
        if self.current_sura is not None:
            self.show_sura(self.current_sura + 1)

    def _start(self):
        self._adjust_page(self.adjustment.lower - self.adjustment.value)

    def _end(self):
        self._adjust_page(self.adjustment.upper - self.adjustment.value
                          - self.adjustment.page_size)

    def _quit(self, *args):
        gtk.main_quit()

    def _redraw(self):
        self.window.queue_draw()

    def _clear_number(self):
        self.number = None

    def _goto_mark(self, name, location=0.0):
        textbuffer = self.text_view.get_buffer()
        mark = textbuffer.get_mark(name)
        if mark is not None:
            self.text_view.scroll_to_mark(mark, 0, True, 0.0, location)

    def show_aya(self, number):
        if self.current_sura is None:
            return
        if 0 < number <= len(self.quran.suras[self.current_sura].ayas):
            self._goto_mark(str(number))
            self.current_aya = number
            self._run_hook('gtk.aya_hook', [str(self.current_sura),
                                            str(self.current_aya)])

    @prefixed(_('aya'))
    def _goto_aya(self, number):
        self.show_aya(number)

    def _next_aya(self):
        self.show_aya(self.current_aya + 1)

    def _prev_aya(self):
        self.show_aya(self.current_aya - 1)

    def _current_aya(self):
        self.show_aya(self.current_aya)

    @prefixed(_('aya'))
    def _goto_before_aya(self, number):
        self._goto_mark(str(number), location=1.0)

    def run(self):
        self.window.show_all()
        gtk.main()

    def _run_hook(self, name, args):
        hook = uihelpers.get_option(self.config, name)
        if hook:
            subprocess.Popen(args=[hook] + args)

    keys = {gtk.keysyms.Prior: _prev_page, gtk.keysyms.Next: _next_page,
            gtk.keysyms.Down: _next_line, gtk.keysyms.Up: _prev_line,
            gtk.keysyms.Home: _start, gtk.keysyms.End: _end,
            ord('j'): _next_line, ord('k'): _prev_line,
            ord(' '): _next_page, ord('q'): _quit, ord('r'): _show_home,
            ord('c'): _ask_sura, ord('a'): _goto_aya,
            ord('b'): _goto_before_aya, ord('s'): _goto_sura,
            ord('n'): _next_aya, ord('p'): _prev_aya, ord('.'): _current_aya,
            gtk.keysyms.Return: _goto_aya, gtk.keysyms.Escape: _clear_number}
    c_keys = {ord('v'): _next_page, ord('n'): _next_line,
              ord('p'): _prev_line, ord('a'): _start, ord('e'): _end,
              ord('l'): _redraw, ord('g'): _clear_number,
              ord('j'): _next_sura, ord('k'): _prev_sura,
              gtk.keysyms.Return: _goto_sura}
    m_keys = {ord('v'): _prev_page, ord('g'): _goto_aya,
              ord('G'): _goto_before_aya}
    s_keys = {ord(' '): _prev_page, gtk.keysyms.Return: _goto_before_aya,
              ord('J'): _goto_juz}
    cm_keys = {ord('p'): _prev_sura, ord('n'): _next_sura,
               gtk.keysyms.Return: _goto_juz,
               ord('g'): _goto_sura, ord('G'): _goto_juz}


class SurasDialog(object):

    def __init__(self, config, quran):
        self.dialog = gtk.Dialog()
        self.dialog.set_title('Noor - ' + _('Choose Sura'))
        self.dialog.set_border_width(1)
        self.dialog.set_size_request(400, 200)
        self.dialog.connect('destroy', self._quit)

        l = gtk.Label()
        l.set_markup(_('Choose a sura to display:'))
        self.combobox = gtk.combo_box_entry_new_text()
        arabic = uihelpers.get_option(config, 'common.arabic_numbers',
                                      False, type='boolean')
        for index, sura in enumerate(quran.suras):
            n = uihelpers._int_to_str(index + 1, arabic=arabic)
            self.combobox.append_text('%s - %s' % (n, sura.name))
        self.combobox.set_active(0)

        button = gtk.Button()
        button.connect('clicked', self._selected)
        button_label = gtk.Label()
        button_label.set_markup(_('Choose'))
        button.add(button_label)
        font1 = _get_font(config, 'gtk.translation_font')
        font2 = _get_font(config, 'gtk.font')
        _modify_font(self.combobox, font2)
        _modify_font(self.combobox.child, font2)
        _modify_font(l, font1)
        _modify_font(button_label, font1)

        self.dialog.vbox.pack_start(l, True, True, 0)
        self.dialog.vbox.pack_start(self.combobox, True, True, 0)
        self.dialog.vbox.pack_start(button, True, True, 0)
        self.selected = False

    def _quit(self, *args):
        gtk.main_quit()

    def _selected(self, *args):
        self.selected = True
        self.dialog.hide()
        self._quit()

    def run(self):
        self.dialog.show_all()
        gtk.main()

    def get_sura(self):
        if self.selected:
            return self.combobox.get_active() + 1

def _get_font(config, name='gtk.font'):
    raw_font = uihelpers.get_option(config, name, None)
    if raw_font is not None:
        font = uihelpers.parse_font(raw_font)
        return pango.FontDescription(font.face + ' ' + font.size)

def _modify_font(widget, font):
    if font is not None:
        widget.modify_font(font)


def _ask_sura(config, quran):
    dialog = SurasDialog(config, quran)
    dialog.run()
    return dialog.get_sura()


def _ask_number(config, name):
    dialog = gtk.Dialog()
    dialog.set_title('Noor - ' + _('Which %s?') % name)
    dialog.set_border_width(1)
    dialog.set_size_request(210, 145)
    def quit(*args, **kwds):
        dialog.hide()
        if not kwds.get('done', False):
            entry.set_text('')
        gtk.main_quit()
    dialog.connect('destroy', lambda *args: quit())
    dialog.connect('delete_event', lambda *args: quit())
    box = dialog.vbox
    l = gtk.Label()
    l.set_markup(_('Which %s?') % name)
    box.add(l)
    entry = gtk.Entry()
    entry.set_max_length(5)
    def selected(*args):
        quit(done=True)
    entry.connect('activate', selected)
    font = _get_font(config, 'gtk.translation_font')
    _modify_font(entry, font)
    _modify_font(l, font)
    box.add(entry)
    dialog.show_all()
    gtk.main()
    try:
        return int(entry.get_text())
    except ValueError:
        return 0

def _insert_home(view):
    view.set_editable(False)
    view.set_cursor_visible(False)
    view.set_wrap_mode(gtk.WRAP_WORD)
    buffer = view.get_buffer()
    tag1 = buffer.create_tag('noor', font='irannastaliq 55',
                             foreground='#AAFFAA', justification='center')
    tag2 = buffer.create_tag('version', font='irannastaliq 20',
                             foreground='#BBBBAA', justification='center')
    tag3 = buffer.create_tag('info', font='mono 13')
    tag4 = buffer.create_tag('copyright', font='15')
    noor_text = _('Noor')
    version = uihelpers._int_to_str(noor.VERSION, arabic=True)
    buffer.insert_with_tags(buffer.get_end_iter(),
                            '\n%s    ' % noor_text, tag1)
    buffer.insert_with_tags(buffer.get_end_iter(),
                            ' %s\n\n\n' % version, tag2)
    info = 'Homepage:     http://noor.sf.net\n' + \
           'Mailing list: http://groups.google.com/group/noor-dev' + \
           ' <noor-dev@googlegroups.com>\n' + \
           'Source repo:  http://noor.sf.net/hg/noor\n\n'
    buffer.insert_with_tags(buffer.get_end_iter(), info, tag3)
    buffer.insert_with_tags(buffer.get_end_iter(), noor.COPYRIGHT, tag4)


def show(sura=None, aya=None):
    config = uihelpers.get_config()
    quran = uihelpers.get_quran(config)
    uihelpers.set_lang(config)
    window = NoorWindow(config, quran, sura)
    if sura is None and uihelpers.get_option(
       config, 'gtk.ask_sura_at_start', True, type='boolean'):
        sura = _ask_sura(config, quran)
    if sura is not None:
        window.show_sura(sura)
    if aya is not None:
        window.show_aya(aya)
    window.run()


def print_usage():
    print 'Usage: %s [sura_number] [aya_number]' % sys.argv[0]
    sys.exit(1)

if __name__ == '__main__':
    sura = None
    aya = None
    if len(sys.argv) > 1:
        if not sys.argv[1].isdigit():
            print_usage()
        sura = int(sys.argv[1])
    if len(sys.argv) > 2:
        if not sys.argv[2].isdigit():
            print_usage()
        aya = int(sys.argv[2])
    show(sura, aya)