~kazam-team/kazam/stable

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
# -*- coding: utf-8 -*-
#
#       prefs.py
#
#       Copyright 2012 David Klasinc <bigwhale@lubica.net>
#
#       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, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import os
import logging
from os.path import expanduser
from gettext import gettext as _
from xdg.BaseDirectory import xdg_config_home

from gi.repository import Gdk, GdkX11

from kazam.backend.config import KazamConfig


class Prefs():
    def __init__(self):
        """Initialize prefs and set all the preference variables to their
           default values.

        Args:
            None

        Returns:
            None

        Raises:
            None
        """
        self.logger = logging.getLogger("Prefs")

        #
        # GUI preferences and stuff
        #
        self.capture_cursor = False
        self.capture_speakers = False
        self.capture_microphone = False

        self.capture_cursor_pic = False
        self.capture_borders_pic = False

        self.countdown_timer = 5

        self.speakers_source = None
        self.microphone_source = None

        self.speakers_volume = 0
        self.microphone_volume = 0

        self.countdown_splash = True
        self.silent_start = False

        #
        # Other stuff
        #
        self.datadir = None

        #
        # Capture related stuff
        #
        self.codec = None
        self.pa_q = None
        self.framerate = 15
        self.autosave_video = False
        self.autosave_video_dir = None
        self.autosave_video_file = None

        self.autosave_picture = False
        self.autosave_picture_dir = None
        self.autosave_picture_file = None
        self.shutter_sound = True
        self.shutter_type = 0
        self.shutter_sound_file = ""

        self.area = None
        self.xid = None
        self.xid_geometry = None

        #
        # Audio sources
        #  - Tuple of all sources
        #  - Selected first source
        #  - Selected second source
        #
        self.audio_sources = None
        self.audio_source = None
        self.audio2_source = None

        self.speaker_sources = []
        self.mic_sources = []

        #
        # Command line parameters
        #
        self.debug = False
        self.test = False
        self.dist = ('Ubuntu', '12.10', 'quantal')
        self.silent = False
        self.sound = True
        self.first_run = True

        self.config = KazamConfig()

        self.read_config()

        self.get_dirs()

        #
        # Fix codec list
        #


    def get_audio_sources(self):
        self.logger.debug("Getting Audio sources.")
        try:
            self.audio_sources = prefs.pa_q.get_audio_sources()
            for src in self.audio_sources:
                if "Monitor" in src[2]:
                    self.speaker_sources.append(src)
                else:
                    self.mic_sources.append(src)

            if prefs.debug:
                for src in self.audio_sources:
                    self.logger.debug(" Device found: ")
                    for item in src:
                        self.logger.debug("  - {0}".format(item))
        except:
            # Something went wrong, just fallback to no-sound
            self.logger.warning("Unable to find any audio devices.")
            self.audio_sources = [[0, _("Unknown"), _("Unknown")]]

    def get_dirs(self):
        paths = {}
        f = None
        try:
            f = open(os.path.join(xdg_config_home, "user-dirs.dirs"))
            for la in f:
                if la.startswith("XDG_VIDEOS") or la.startswith("XDG_DOCUMENTS") or la.startswith("XDG_PICTURES"):
                    (idx, val) = la.strip()[:-1].split('="')
                    paths[idx] = os.path.expandvars(val)
        except:
            paths['XDG_VIDEOS_DIR'] = os.path.expanduser("~/Videos/")
            paths['XDG_PICTURES_DIR'] = os.path.expanduser("~/Pictures/")
            paths['XDG_DOCUMENTS_DIR'] = os.path.expanduser("~/Documents/")
        finally:
            if f is not None:
                f.close()

        paths['HOME_DIR'] = os.path.expandvars("$HOME")

        if 'XDG_VIDEOS_DIR' in paths and os.path.isdir(paths['XDG_VIDEOS_DIR']):
            self.video_dest = paths['XDG_VIDEOS_DIR']
        elif 'XDG_DOCUMENTS_DIR' in paths and os.path.isdir(paths['XDG_DOCUMENTS_DIR']):
            self.video_dest = paths['XDG_DOCUMENTS_DIR']
        elif 'HOME_DIR' in paths and os.path.isdir(paths['HOME_DIR']):
            self.video_dest = paths['HOME_DIR']
        else:
            self.video_dest = expanduser("~")

        if 'XDG_PICTURES_DIR' in paths and os.path.isdir(paths['XDG_PICTURES_DIR']):
            self.logger.debug("XDG_PICTURES is a directory and accessible")
            self.picture_dest = paths['XDG_PICTURES_DIR']
        elif 'XDG_DOCUMENTS_DIR' in paths and os.path.isdir(paths['XDG_DOCUMENTS_DIR']):
            self.logger.debug("XDG_DOCUMENTS is a directory and accessible")
            self.picture_dest = paths['XDG_DOCUMENTS_DIR']
        elif 'HOME_DIR' in paths and os.path.isdir(paths['HOME_DIR']):
            self.logger.debug("HOME_DIR is a directory and accessible")
            self.picture_dest = paths['HOME_DIR']
        else:
            self.logger.debug("Fallback to ~ for save files.")
            self.picture_dest = expanduser("~")

    def get_sound_files(self):
        self.sound_files = []
        for root, d_dir, files in os.walk(os.path.join(self.datadir, "sounds")):
            for f_file in files:
                if f_file.endswith('.ogg'):
                    self.sound_files.append(f_file)

    def read_config(self):
        self.audio_source = int(self.config.get("main", "audio_source"))
        self.audio2_source = int(self.config.get("main", "audio2_source"))
        self.main_x = int(self.config.get("main", "last_x"))
        self.main_y = int(self.config.get("main", "last_y"))
        self.countdown_timer = float(self.config.get("main", "counter"))

        #
        # Just in case this blows up in our face later
        #
        if self.countdown_timer > 10:
            self.countdown_timer = 10
        self.framerate = float(self.config.get("main", "framerate"))

        self.capture_cursor = self.config.getboolean("main", "capture_cursor")
        self.capture_microphone = self.config.getboolean("main", "capture_microphone")
        self.capture_speakers = self.config.getboolean("main", "capture_speakers")

        self.capture_cursor_pic = self.config.getboolean("main", "capture_cursor_pic")
        self.capture_borders_pic = self.config.getboolean("main", "capture_borders_pic")

        self.countdown_splash = self.config.getboolean("main", "countdown_splash")

        self.autosave_video = self.config.getboolean("main", "autosave_video")
        self.autosave_video_dir = self.config.get("main", "autosave_video_dir")
        self.autosave_video_file = self.config.get("main", "autosave_video_file")

        self.autosave_picture = self.config.getboolean("main", "autosave_picture")
        self.autosave_picture_dir = self.config.get("main", "autosave_picture_dir")
        self.autosave_picture_file = self.config.get("main", "autosave_picture_file")

        self.shutter_sound = self.config.getboolean("main", "shutter_sound")
        self.shutter_type = int(self.config.get("main", "shutter_type"))

        self.first_run = self.config.getboolean("main", "first_run")

        #
        # Determine which codec to use
        #
        if self.first_run:
            self.logger.debug("First run detected.")
            self.config.set("main", "first_run", False)
            self.config.write()

            codecs_avail = detect_codecs()
            if CODEC_H264 in codecs_avail:
                self.codec = CODEC_H264
                self.logger.debug("Setting H264 as default codec.")
            elif CODEC_VP8 in codecs_avail:
                self.codec = CODEC_VP8
                self.logger.debug("Setting VP8 as default codec.")
            else:
                self.codec = CODEC_RAW
                self.logger.debug("Setting RAW as default codec.")
        else:
            self.codec = int(self.config.get("main", "codec"))

    def save_config(self):
        self.config.set("main", "capture_cursor", self.capture_cursor)
        self.config.set("main", "capture_speakers", self.capture_speakers)
        self.config.set("main", "capture_microphone", self.capture_microphone)

        self.config.set("main", "capture_cursor_pic", self.capture_cursor_pic)
        self.config.set("main", "capture_borders_pic", self.capture_borders_pic)

        self.config.set("main", "last_x", self.main_x)
        self.config.set("main", "last_y", self.main_y)

        if self.sound:
            self.config.set("main", "audio_source", self.audio_source)
            self.config.set("main", "audio2_source", self.audio2_source)

        self.config.set("main", "countdown_splash", self.countdown_splash)
        self.config.set("main", "counter", self.countdown_timer)
        self.config.set("main", "codec", self.codec)
        self.config.set("main", "framerate", self.framerate)
        self.config.set("main", "autosave_video", self.autosave_video)
        self.config.set("main", "autosave_video_dir", self.autosave_video_dir)
        self.config.set("main", "autosave_video_file", self.autosave_video_file)
        self.config.set("main", "autosave_picture", self.autosave_picture)
        self.config.set("main", "autosave_picture_dir", self.autosave_picture_dir)
        self.config.set("main", "autosave_picture_file", self.autosave_picture_file)
        self.config.set("main", "shutter_sound", self.shutter_sound)
        self.config.set("main", "shutter_type", self.shutter_type)

        self.config.write()

class hw:
    def __init__(self):
        self.logger = logging.getLogger("Prefs-HW")
        self.logger.debug("Getting hardware specs")
        self.screens = None
        self.combined_screen = None

        self.get_screens()

    def get_current_screen(self, window = None):
        try:
            if window:
                screen = self.default_screen.get_monitor_at_window(window.get_window())
            else:
                disp = GdkX11.X11Display.get_default()
                dm = Gdk.Display.get_device_manager(disp)
                pntr_device = dm.get_client_pointer()
                (src, x, y) = pntr_device.get_position()
                screen = self.default_screen.get_monitor_at_point(x, y)
        except:
            screen = 0
        return screen

    def get_screens(self):
        try:
            self.logger.debug("Getting Video sources.")
            self.screens = []
            self.default_screen = Gdk.Screen.get_default()
            self.logger.debug("Found {0} monitor(s).".format(self.default_screen.get_n_monitors()))

            for i in range(self.default_screen.get_n_monitors()):
                rect = self.default_screen.get_monitor_geometry(i)
                self.logger.debug("  Monitor {0} - X: {1}, Y: {2}, W: {3}, H: {4}".format(i,
                                                                                          rect.x,
                                                                                          rect.y,
                                                                                          rect.width,
                                                                                          rect.height))
                self.screens.append({"x": rect.x,
                                     "y": rect.y,
                                     "width": rect.width,
                                     "height": rect.height})

            if self.default_screen.get_n_monitors() > 1:
                self.combined_screen = {"x": 0, "y": 0,
                                        "width": self.default_screen.get_width(),
                                        "height": self.default_screen.get_height()}
                self.logger.debug("  Combined screen - X: 0, Y: 0, W: {0}, H: {1}".format(self.default_screen.get_width(),
                                                                                          self.default_screen.get_height()))
            else:
                self.combined_screen = None

        except:
            self.logger.warning("Unable to find any video sources.")


def detect_codecs():
    logger = logging.getLogger("Prefs-DC")
    from gi.repository import Gst

    Gst.init(None)

    codecs_supported = []
    codec_test = None
    for codec in CODEC_LIST:
        logger.debug("Testing for: {0}".format(codec[2]))
        if codec[0]:
            try:
                codec_test = Gst.ElementFactory.make(codec[1], "video_encoder")
                logger.debug("Error loading {0} GStreamer plugin - support disabled.".format(codec))
            except:
                codec_test = None

            if codec_test:
                codecs_supported.append(codec[0])
                logger.debug("Supported encoder: {0}.".format(codec[2]))
            else:
                logger.debug("Unable to find {0} GStreamer plugin - support disabled.".format(codec))

        else:
            # RAW codec is None, so we don't try to load it.
            codecs_supported.append(codec[0])
            logger.debug("Supported encoder: {0}.".format(codec[2]))
        codec_test = None
    return codecs_supported


def get_codec(codec):
    for c in CODEC_LIST:
        if c[0] == codec:
            return c
    return None


#
# The dreaded constants, we like those from time to time. Really.
#
# Codecs

CODEC_RAW = 0
CODEC_VP8 = 1
CODEC_H264 = 2
CODEC_HUFF = 3
CODEC_JPEG = 4

#
# Number, gstreamer element name, string description, file extension, advanced
#

CODEC_LIST = [[0, None, 'RAW (AVI)', '.avi', True],
              [1, 'vp8enc', 'VP8 (WEBM)', '.webm', False],
              [2, 'x264enc', 'H264 (MP4)', '.mp4', False],
              [3, 'avenc_huffyuv', 'HUFFYUV (AVI)', '.avi', True],
              [4, 'avenc_ljpeg', 'Lossless JPEG (AVI)', '.avi', True],
              ]

# PulseAudio Error Codes
PA_LOAD_ERROR = 1
PA_GET_STATE_ERROR = 2
PA_STARTUP_ERROR = 3
PA_UNABLE_TO_CONNECT = 4
PA_UNABLE_TO_CONNECT2 = 5
PA_MAINLOOP_START_ERROR = 6
PA_GET_SOURCES_ERROR = 7
PA_GET_SOURCES_TIMEOUT = 8
PA_GET_SOURCE_ERROR = 9
PA_GET_SOURCE_TIMEOUT = 10
PA_MAINLOOP_END_ERROR = 11

# PulseAudio Status Codes
PA_STOPPED = 0
PA_WORKING = 1
PA_FINISHED = 2
PA_ERROR = 3

# PulseAudio State Codes
PA_STATE_READY = 0
PA_STATE_BUSY = 1
PA_STATE_FAILED = 2
PA_STATE_WORKING = 3

# Various actions
ACTION_SAVE = 0
ACTION_EDIT = 1

# Blink modes and states
BLINK_STOP = 0
BLINK_START = 1
BLINK_SLOW = 2
BLINK_FAST = 3
BLINK_STOP_ICON = 4
BLINK_READY_ICON = 5

# Main modes
MODE_SCREENCAST = 0
MODE_SCREENSHOT = 1

# Record modes
MODE_FULL = 0
MODE_ALL = 1
MODE_AREA = 2
MODE_WIN = 3
MODE_ACTIVE = 4
MODE_GOD = 666

# Area resize handles
HANDLE_TL = 0
HANDLE_TC = 1
HANDLE_TR = 2
HANDLE_CL = 3
HANDLE_MOVE = 4
HANDLE_CR = 5
HANDLE_BL = 6
HANDLE_BC = 7
HANDLE_BR = 8

# Area resize handle cursors
HANDLE_CURSORS = (
    Gdk.CursorType.TOP_LEFT_CORNER,
    Gdk.CursorType.TOP_SIDE,
    Gdk.CursorType.TOP_RIGHT_CORNER,
    Gdk.CursorType.LEFT_SIDE,
    Gdk.CursorType.FLEUR,
    Gdk.CursorType.RIGHT_SIDE,
    Gdk.CursorType.BOTTOM_LEFT_CORNER,
    Gdk.CursorType.BOTTOM_SIDE,
    Gdk.CursorType.BOTTOM_RIGHT_CORNER
)


#
# Singletons, because we also like singletons from time to time ... :)
#

prefs = Prefs()
HW = hw()