~thomas-deruyter-3/qreator/qreator

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
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2012 David Planella <david.planella@ubuntu.com>
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.
### END LICENSE

import cairo
import math
from gi.repository import Gtk, Gdk, GdkPixbuf  # pylint: disable=E0611
from gi.repository import GtkChamplain, Clutter, Champlain
from gi.repository import NetworkManager, NMClient
import logging
logger = logging.getLogger('qreator')

from qreator_lib.i18n import _
from qreator_lib import Window
from qreator_lib.helpers import get_media_file as get_media_file

import sys
sys.path.insert(0, "/usr/share/software-center/")
import softwarecenter.db.database
import defer

from QRCode import QRCode as QRCode
from QRCode import QRCodeOutput as QRCodeOutput

COL_DESC = 0
COL_PIXBUF = 1
COL_CALLBACK = 2

PAGE_NEW = 0
#PAGE_HISTORY = 1
#PAGE_SETTINGS = 2
PAGE_ABOUT = 1
PAGE_QR = 2


# See qreator_lib.Window.py for more details about how this class works
class QreatorWindow(Window):
    __gtype_name__ = "QreatorWindow"

    def finish_initializing(self, builder):  # pylint: disable=E1002
        """Set up the main window"""
        super(QreatorWindow, self).finish_initializing(builder)

        # Code for other initialization actions should be added here.

        # Initialize the clipboard
        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

        # Initialize the style for the main toolbar
        context = self.ui.toolbar1.get_style_context()
        context.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)

        # Initialize the Cairo surface that will contain the QR code
        self.surface = None

        # Hide the notebook tabs
        self.ui.notebook1.set_show_tabs(False)

        # Initialize combo boxes
        self.ui.comboboxtextSecurity.set_active(0)
        self.ui.comboboxtextProtocol.set_active(0)

        # Initialize placeholder text (we need to do that because due to
        # a Glade bug they are otherwise not marked as translatable)
        self.ui.entryURL.set_placeholder_text(_('[URL]'))
        self.ui.entrySSID.set_placeholder_text(
            _('[Network identifier - expand for autodetection]'))
        self.ui.entryPassword.set_placeholder_text(_('[Network password]'))

        # Initialize about dialog
        about = Gtk.AboutDialog()
        about.set_program_name("Qreator")
        about.set_copyright(
            "Copyright (c) 2012 David Planella" +
            "\nhttp://about.me/david.planella")
        about.set_website("https://launchpad.net/qreator")

        about.set_version('12.05.5')
        about.set_authors([
            'David Planella <david.planella@ubuntu.com>',
            'Michael Hall <mhall119@ubuntu.com>',
            'Andrew Starr-Bochicchio <andrewsomething@ubuntu.com >',
            ])
        about.set_license(_('Distributed under the GPL v3 license.') +
                '\nhttp://www.opensource.org/licenses/gpl-3.0.html')

        about.set_translator_credits(_("translator-credits"))

        box = builder.get_object("about_box")
        about.vbox.reparent(box)

        # Get rid of the 'Close' button
        for button in about.action_area.get_children():
            if button.get_property('label') == 'gtk-close':
                button.destroy()

        # Initialize the Software Center apps autocompletion
        self.softwarecenterapps = None

        self.usc_apps_complete = Complete()

        self.usc_apps_complete.set_hexpand(True)
        self.usc_apps_complete.connect("changed",
                                    self.on_usc_apps_complete_changed, None)

        #self.get_softwarecenterapps()
        #self.on_get_softwarecenterapps()
        deferred = defer.defer(self.get_softwarecenterapps)
        deferred.add_callback(self.on_get_softwarecenterapps)

        self.ui.qr_app.attach(self.usc_apps_complete, 1, 0, 1, 1)

        # Load the background texture
        self.texture = cairo.ImageSurface.create_from_png(
                                                get_media_file("pattern.png"))

        # Set up the QR types shown in the main icon view
        self.ui.qr_types_view.set_text_column(COL_DESC)
        self.ui.qr_types_view.set_pixbuf_column(COL_PIXBUF)

        self.qr_types = [
            {'desc': _('URL'),
                'icon': GdkPixbuf.Pixbuf.new_from_file(get_media_file(
                            'url.png')),
                'callback': 'on_qr_url_clicked'},
            {'desc': _('Text'),
                'icon': GdkPixbuf.Pixbuf.new_from_file(get_media_file(
                            'text.png')),
                'callback': 'on_qr_text_clicked'},
            {'desc': _('Geolocation'),
                'icon': GdkPixbuf.Pixbuf.new_from_file(get_media_file(
                            'location.png')),
                'callback': 'on_qr_location_clicked'},
            {'desc': _('Wifi network'),
                'icon': GdkPixbuf.Pixbuf.new_from_file(get_media_file(
                            'wifi.png')),
                'callback': 'on_qr_wifi_clicked'},
            {'desc': _('Ubuntu Software Center app'),
                'icon': GdkPixbuf.Pixbuf.new_from_file(get_media_file(
                            'softwarecentre.png')),
                'callback': 'on_qr_softwarecenterapp_clicked'},
        ]

        self.qr_types_store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, str)
        # ^ desc, icon, callback ^
        self.qr_types_store.set_sort_column_id(COL_DESC,
                                               Gtk.SortType.ASCENDING)
        self.ui.qr_types_view.set_model(self.qr_types_store)
        self.fill_qr_types_store()

        self.curr_height = 0
        self.curr_width = 0

        # Add an initial text, so that there is an initial QR code
        self.qr_code_placeholder = 'http://launchpad.net/qreator'

    def fill_qr_types_store(self):
        self.qr_types_store.clear()

        for qr_type in self.qr_types:
            self.qr_types_store.append([qr_type['desc'],
                                        qr_type['icon'],
                                        qr_type['callback']])

    def on_qreator_window_check_resize(self, widget):
        '''We need this function to fix the issue described at
        http://bit.ly/LW94BO whereby the number of columns of the icon view
        widget stays fixed at the number set for the initial width of the
        window'''
        # Get the new size
        new_width = widget.get_size()[0]
        new_height = widget.get_size()[1]
        # If the size has changed...
        if(new_width != self.curr_width or new_height != self.curr_height):
            # Remember new size
            self.curr_width = new_width
            self.curr_height = new_height
            # and refill iconviews with icons to adjust columns number
            self.fill_qr_types_store()

    def on_entryText_changed(self, widget, data=None):
        self.update_qr_code(widget.get_text(widget.get_start_iter(),
                                            widget.get_end_iter(),
                                            False))

    def on_map_widget_button_press_event(self, actor, event, view):
        x, y = event.get_coords()
        lat, lon = view.x_to_longitude(x), view.y_to_latitude(y)

        self.ui.lat_entry.set_text(str(lat))
        self.ui.lon_entry.set_text(str(lon))

        self.update_qr_code('geo:{0},{1}'.format(str(lon), str(lat)))

        return True

    def on_toolbuttonNew_clicked(self, widget, data=None):
        '''Shows the home page'''
        self.ui.notebook1.set_current_page(PAGE_NEW)

    def on_toolbuttonHistory_clicked(self, widget, data=None):
        '''Shows the history page'''
        pass  # self.ui.notebook1.set_current_page(PAGE_HISTORY)

    def on_toolbuttonSettings_clicked(self, widget, data=None):
        '''Shows the settings page'''
        pass  # self.ui.notebook1.set_current_page(PAGE_SETTINGS)

    def on_toolbuttonAbout_clicked(self, widget, data=None):
        '''Shows the about page'''
        self.ui.notebook1.set_current_page(PAGE_ABOUT)

    def _hide_children(self, widget):
        for child in widget.get_children():
            child.hide()

    def on_qr_url_clicked(self):
        self._hide_children(self.ui.qr_input)
        self.ui.qr_url.show_all()

    def on_qr_wifi_clicked(self):
        self._hide_children(self.ui.qr_input)
        self.ui.qr_wifi.show_all()

        ssids = get_ssids()
        for ssid in ssids:
            self.ui.comboboxtextSSID.append_text(ssid)

    def on_qr_softwarecenterapp_clicked(self):
        # We're now loading the UI for the Software Center app QR type
        self._hide_children(self.ui.qr_input)
        self.ui.qr_app.show_all()

    def on_qr_text_clicked(self):
        # Initialize multi-line text entry
        textbuffer = self.ui.entryText.get_buffer()
        textbuffer.connect("changed", self.on_entryText_changed, None)

        self._hide_children(self.ui.qr_input)
        self.ui.qr_text.show_all()

    def on_qr_location_clicked(self):
        # We're now loading the UI for the location QR type
        self._hide_children(self.ui.qr_input)
        self.ui.qr_location.show_all()

        map_widget = GtkChamplain.Embed()
        map_widget.set_hexpand(True)
        map_widget.set_vexpand(True)

        map_grid = self.ui.qr_location

        map_grid.set_size_request(-1, 250)
        map_grid.attach(map_widget, 0, 0, 1, 1)

        self.map_view = map_widget.get_view()
        self.map_view.set_reactive(True)
        map_widget.connect('button-release-event',
                           self.on_map_widget_button_press_event,
                           self.map_view)

        # Get the current location, center the map on it, and initialize
        # other map features
        latitude, longitude = get_current_location()
        self.map_view.center_on(latitude, longitude)
        if latitude == 0 and longitude == 0:
            # In case something went wrong in getting the current location
            self.map_view.set_zoom_level(1)
        else:
            self.map_view.set_zoom_level(15)
        self.map_view.set_kinetic_mode(True)

        scale = Champlain.Scale()
        scale.connect_view(self.map_view)
        self.map_view.bin_layout_add(scale, Clutter.BinAlignment.START,
                                     Clutter.BinAlignment.END)

        self.ui.qr_location.show_all()

    def on_qr_types_view_item_activated(self, widget, item):
        '''Loads the UI for the appropriate QR type'''

        model = widget.get_model()
        qr_callback = getattr(QreatorWindow, model[item][COL_CALLBACK])

        qr_callback(self)

        self.ui.notebook1.set_current_page(PAGE_QR)

    def get_pixbuf_from_drawing_area(self):
        window = self.ui.qr_drawingarea.get_window()

        src_x, src_y = self.get_centered_coordinates(self.ui.qr_drawingarea,
                                                     self.surface)
        image_height = self.surface.get_height()
        image_width = self.surface.get_width()

        return Gdk.pixbuf_get_from_window(window, src_x, src_y,
                                          image_width, image_height)

    def on_toolbuttonSave_clicked(self, widget, data=None):
        if not self.surface:
            return

        dialog = Gtk.FileChooserDialog(_("Please choose a file"), self,
            Gtk.FileChooserAction.SAVE,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_SAVE, Gtk.ResponseType.OK))

        filter_png = Gtk.FileFilter()
        filter_png.set_name(_("PNG images"))
        filter_png.add_mime_type("image/png")
        dialog.add_filter(filter_png)

        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            # We cannot write directly from the surface, as the
            # Surface.write_to_png() method writes the image in the original
            # size returned by qrencode (i.e. non-scaled), and the
            # SurfacePattern does not have any methods to write to disk.
            # So we read the contents from the Gtk.DrawingArea, put them into
            # a Gdk.Pixbuf and use its 'savev' method to write to disk.

            pixbuf = self.get_pixbuf_from_drawing_area()

            pixbuf.savev(dialog.get_filename(), 'png', [], [])

        dialog.destroy()

    def on_toolbuttonCopy_clicked(self, widget, data=None):
        if not self.surface:
            return

        pixbuf = self.get_pixbuf_from_drawing_area()
        self.clipboard.set_image(pixbuf)

    def update_qr_code(self, text):
        self.qr_code_placeholder = text
        self.ui.qr_drawingarea.queue_draw()

    def on_usc_apps_complete_changed(self, widget, data=None):
        USC_APPS_BASE_URL = 'https://apps.ubuntu.com/cat/applications/'
        self.update_qr_code(USC_APPS_BASE_URL + widget.get_text())

    def on_entryURL_changed(self, widget, data=None):
        self.update_url_qr_code(www=widget.get_text())

    def on_comboboxtextProtocol_changed(self, widget, data=None):
        self.update_url_qr_code(protocol=widget.get_active_text())

    def update_url_qr_code(self, protocol=None, www=None):
        if not protocol:
            protocol = self.ui.comboboxtextProtocol.get_active_text()
        if not www:
            www = self.ui.entryURL.get_text()

        if not protocol or www == '':
            return

        self.update_qr_code(protocol + www)

    def update_wifi_qr_code(self, security=None, ssid=None, password=None):
        if not security:
            security = self.ui.comboboxtextSecurity.get_active_text()
        if not ssid:
            ssid = self.ui.entrySSID.get_text()
        if not password:
            password = self.ui.entryPassword.get_text()

        if not security or ssid == '' or password == '':
            return

        wifi_qr_code = 'WIFI:T:{0};S:{1};P:{2};;'.format(security, ssid,
                                                         password)
        self.update_qr_code(wifi_qr_code)

    def on_comboboxtextSecurity_changed(self, widget, data=None):
        self.update_wifi_qr_code(security=widget.get_active_text())

    def on_entrySSID_changed(self, widget, data=None):
        self.update_wifi_qr_code(ssid=widget.get_text())

    def on_comboboxtextSSID_changed(self, widget, data=None):
        self.update_wifi_qr_code(ssid=widget.get_active_text())

    def on_entryPassword_changed(self, widget, data=None):
        self.update_wifi_qr_code(password=widget.get_text())

    def on_checkbutton1_clicked(self, widget):
        if widget.get_active():
            self.ui.entryPassword.set_visibility(True)
        else:
            self.ui.entryPassword.set_visibility(False)

    def get_centered_coordinates(self, drawing_area, surface):

        drawing_area_height = drawing_area.get_allocated_height()
        drawing_area_width = drawing_area.get_allocated_width()
        image_height = surface.get_height()
        image_width = surface.get_width()

        return (drawing_area_width / 2 - image_width / 2,
                drawing_area_height / 2 - image_height / 2)

    def on_qr_drawingarea_draw(self, widget, ctx, data=None):
        text = self.qr_code_placeholder
        if text == '':
            return

        ## Fill the background

        # Create a rounded rectanble
        x = 0.0
        y = 0.0
        width = widget.get_allocated_width()
        height = widget.get_allocated_height()
        aspect = 1.0
        corner_radius = height / 50.0

        radius = corner_radius / aspect
        degrees = math.pi / 180.0

        ctx.new_sub_path()
        ctx.arc(x + width - radius, y + radius, radius, -90 * degrees,
                0 * degrees)
        ctx.arc(x + width - radius, y + height - radius, radius, 0 * degrees,
                90 * degrees)
        ctx.arc(x + radius, y + height - radius, radius, 90 * degrees,
                180 * degrees)
        ctx.arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
        ctx.close_path()

        # Fill the rounded rectangle with a linear gradient
        lg = cairo.LinearGradient(0.0, 0.0, 500.0, 500.0)
        lg.add_color_stop_rgba(0, 0.27, 0.27, 0.27, 1)  # 1,1,1 is white
        lg.add_color_stop_rgba(1, 0.22, 0.22, 0.22, 1)

        ctx.set_source(lg)
        ctx.fill()

        # Load a texture and overlay it to the gradient, tiled
        pattern = cairo.SurfacePattern(self.texture)
        pattern.set_extend(cairo.EXTEND_REPEAT)
        ctx.set_source(pattern)
        ctx.paint()

        ## Create the QR code
        qr_code = QRCode()
        self.surface = qr_code.encode(text, QRCodeOutput.CAIRO_SURFACE)

        # Center the image in the drawing area
        centered_width, centered_height = \
            self.get_centered_coordinates(widget, self.surface)
        ctx.translate(centered_width, centered_height)

        # Set the surface as the context's source
        ctx.set_source_surface(self.surface)

        # Render the image
        ctx.paint()

    def get_softwarecenterapps(self):
        print 'Task STARTED!'
        db = softwarecenter.db.database.StoreDatabase()
        db._aptcache.open()
        db.open(use_axi=False, use_agent=False)
        apps = []
        for doc in db:
            app = db.get_application(doc)
            appdetails = app.get_details(db)
            appinfo = App(app.appname, app.pkgname, appdetails.icon)
            apps.append(appinfo)
        self.softwarecenterapps = apps
        return apps

    def on_get_softwarecenterapps(self, result):
        print 'Task FINISHED!'
        self.usc_apps_complete.add(self.softwarecenterapps)


def get_current_location():
    '''Gets the current location from geolocation via IP (only method
       currently supported)'''
    #import Geoclue
    #POS_PROVIDER = 'Ubuntu GeoIP'
    #location = Geoclue.DiscoverLocation()
    #location.init()
    #location.set_position_provider(POS_PROVIDER)
    #position = location.get_location_info()

    import dbus
    bus = dbus.SessionBus()
    geoclue = bus.get_object(
        'org.freedesktop.Geoclue.Providers.UbuntuGeoIP',
        '/org/freedesktop/Geoclue/Providers/UbuntuGeoIP')
    position_info = geoclue.GetPosition(
        dbus_interface='org.freedesktop.Geoclue.Position')

    position = {}
    position['timestamp'] = position_info[1]
    position['latitude'] = position_info[2]
    position['longitude'] = position_info[3]
    position['altitude'] = position_info[4]

    return position['latitude'], position['longitude']


def get_ssids():
    nmc = NMClient.Client.new()
    devs = nmc.get_devices()

    ssids = []
    for dev in devs:
        if dev.get_device_type() == NetworkManager.DeviceType.WIFI:
            for ap in dev.get_access_points():
                ssids.append(ap.get_ssid())

    return ssids


class App(object):
    def __init__(self, name, package, icon):
        self.name = name
        self.package = package
        self.icon = icon


class Complete(Gtk.Entry):
    '''a class to autocomplete'''

    def __init__(self, apps=None):
        Gtk.Entry.__init__(self)
        self.completion = Gtk.EntryCompletion()
        self.set_completion(self.completion)
        self.model = Gtk.ListStore(str, GdkPixbuf.Pixbuf, str)
        self.completion.set_model(self.model)
        self.completion_img = Gtk.CellRendererPixbuf()
        self.completion.pack_start(self.completion_img, True)
        self.completion.add_attribute(self.completion_img, "pixbuf", 1)
        self.completion.set_text_column(0)
        self.completion.set_popup_set_width(False)
        self.completion.set_inline_completion(True)
        self.icons = Gtk.IconTheme.get_default()
        self.icons.append_search_path("/usr/share/app-install/icons/")

        if apps:
            self.add(apps)
        else:
            self.set_placeholder_text(
                _('[Wait a few seconds to enable autocompletion...]'))

    def add(self, apps):
        for app in apps:
            self._remember(app)
        self.set_placeholder_text(
                _('[Type the name of an app]'))

    def _remember(self, app):
        '''add a value to the list of strings to suggest'''
        try:
            icon = self.icons.load_icon(
                "{0}".format(app.icon),
                16, Gtk.IconLookupFlags.USE_BUILTIN)
        except:
            icon = self.icons.load_icon(
                "stock_not",
                16, Gtk.IconLookupFlags.USE_BUILTIN)
        self.model.append([app.package, icon, app.name])