Пример #1
0
 def __init__(self,
              drawable,
              height,
              width,
              y,
              x,
              colour=ui.colour_default,
              monospace_font=None,
              font=None):
     # y and x are in pixels, height and width are in characters
     self.monospace = monospace_font
     self.font = font if font else monospace_font
     fontmap = PangoCairo.font_map_get_default()
     pangoctx = fontmap.create_context()
     metrics = pangoctx.get_metrics(self.monospace)
     self.fontwidth = metrics.get_approximate_digit_width() // Pango.SCALE
     self.ascent = metrics.get_ascent() // Pango.SCALE
     self.descent = metrics.get_descent() // Pango.SCALE
     self.fontheight = self.ascent + self.descent
     super(text_window, self).__init__(drawable, height * self.fontheight,
                                       width * self.fontwidth, y, x)
     self.height_chars = height
     self.width_chars = width
     self.cur_y = 0
     self.cur_x = 0
     self.colour = colour
     self._cursor_on = True
     self._surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width,
                                        self.height)
     self.erase()
Пример #2
0
    def _set_screen_dpi(self):
        dpi = get_screen_dpi()
        if self.hw in [Hardware.XO1, Hardware.XO15, Hardware.XO175]:
            dpi = 133  # Tweak for XO display color mode

        font_map_default = PangoCairo.font_map_get_default()
        font_map_default.set_resolution(dpi)
Пример #3
0
    def __init__(self, monospace_font, font, min_height=24, min_width=80):
        super().__init__()
        self.monospace = monospace_font
        self.font = font if font else monospace_font
        fontmap = PangoCairo.font_map_get_default()
        pangoctx = fontmap.create_context()
        metrics = pangoctx.get_metrics(self.monospace)
        self.fontwidth = metrics.get_approximate_digit_width() // Pango.SCALE
        self.ascent = metrics.get_ascent() // Pango.SCALE
        self.descent = metrics.get_descent() // Pango.SCALE
        self.fontheight = self.ascent + self.descent

        self._contents = []
        self._ontop = []
        self.left = "Quicktill"
        self.middle = ""
        self._cursor_state = False  # Alternates between shown and not-shown
        self._cursor_location = None
        self._cursor_timeout()

        # Set the minimum size
        self.set_size_request(min_width * self.fontwidth,
                              min_height * self.fontheight)

        self.connect("draw", self._redraw)
        self._clockalarm()
Пример #4
0
 def __init__(self, drawable, height, width, y, x,
              colour=ui.colour_default,
              monospace_font=None, font=None):
     # y and x are in pixels, height and width are in characters
     self.monospace = monospace_font
     self.font = font if font else monospace_font
     fontmap = PangoCairo.font_map_get_default()
     pangoctx = fontmap.create_context()
     metrics = pangoctx.get_metrics(self.monospace)
     self.fontwidth = metrics.get_approximate_digit_width() // Pango.SCALE
     self.ascent = metrics.get_ascent() // Pango.SCALE
     self.descent = metrics.get_descent() // Pango.SCALE
     self.fontheight = self.ascent + self.descent
     super().__init__(
         drawable, height * self.fontheight, width * self.fontwidth,
         y, x)
     self.height_chars = height
     self.width_chars = width
     self.cur_y = 0
     self.cur_x = 0
     self.colour = colour
     self._cursor_on = True
     # XXX it should be possible to use a cairo.RecordingSurface
     # here to save memory on surfaces that will be written to on
     # initialisation and which will then be static, but this was
     # introduced in pycairo 1.11.0 and Ubuntu 16.04 to 17.10 only
     # have pycairo-1.10.0.  Ubuntu 18.04 has pycairo-1.16.0 so
     # implement it once all installations have been upgraded!
     self._surface = cairo.ImageSurface(
         cairo.FORMAT_ARGB32, self.width, self.height)
     self.erase()
Пример #5
0
    def __init__(self, monospace_font, font,
                 preferred_height=24, preferred_width=80,
                 minimum_height=14, minimum_width=80):
        super().__init__()
        self.monospace = monospace_font
        self.font = font if font else monospace_font
        fontmap = PangoCairo.font_map_get_default()
        pangoctx = fontmap.create_context()
        metrics = pangoctx.get_metrics(self.monospace)
        self.fontwidth = metrics.get_approximate_digit_width() // Pango.SCALE
        self.ascent = metrics.get_ascent() // Pango.SCALE
        self.descent = metrics.get_descent() // Pango.SCALE
        self.fontheight = self.ascent + self.descent

        self._preferred_height = preferred_height
        self._minimum_height = minimum_height
        self._preferred_width = preferred_width
        self._minimum_width = minimum_width
        self._contents = []
        self._ontop = []
        self.left = "Quicktill"
        self.middle = ""
        self._cursor_state = False # Alternates between shown and not-shown
        self._cursor_location = None
        self._cursor_timeout()

        self.connect("draw", self._redraw)
        self._clockalarm()
Пример #6
0
def fit_text(text, font_name, max_width, max_height):
    """Given some text and a font name, returns a Pango.Layout which is as
       big as possible but still smaller than max_width x max_height.

       Example usage:
       ly = fit_text("The mask.\nThe ray-traced picture.\nAnd finally,\nthe wireframe city.", "Impact", 800, 800)
       sz = ly.get_pixel_size()
       base = cairo.ImageSurface(cairo.FORMAT_ARGB32, sz.width, sz.height)
       base_context = cairo.Context(base)
       PangoCairo.show_layout(base_context, ly)
       base.write_to_png("mytext.png")
    """
    fm = PangoCairo.font_map_get_default()
    fonts = [x.get_name() for x in fm.list_families()]
    if font_name not in fonts:
        raise Exception("Font name '%s' isn't on the fonts list" % font_name)
    ctx = fm.create_context()
    ly = Pango.Layout.new(ctx)
    fd = Pango.FontDescription.new()
    ly.set_single_paragraph_mode(False)
    ly.set_alignment(Pango.Alignment.CENTER)
    fd.set_family(font_name)
    ly.set_text(text, -1)
    # now, binary search to find the biggest integer font size that still fits
    # first, quickly find a setting which is bigger than the right size
    size = 100
    loopcount = 0
    while 1:
        loopcount += 1
        if loopcount > 10000:
            print("Got stuck finding font size; crashing")
            sys.exit(1)
        fd.set_absolute_size(size)
        ly.set_font_description(fd)
        s = ly.get_pixel_size()
        if s.width > max_width or s.height > max_height:
            # this one is bigger, so it's our start point for binary search
            break
        # this one's smaller, so double it and start again
        size = size * 2
    # now, binary search; we know this one's too big
    first = 0
    last = size
    found = False
    loopcount = 1
    while first <= last:
        loopcount += 1
        if loopcount > 10000:
            print("Got stuck finding font size; crashing")
            sys.exit(1)
        midpoint = ((first + last) // 2)
        fd.set_absolute_size(midpoint)
        ly.set_font_description(fd)
        s = ly.get_pixel_size()
        if s.width < max_width and s.height < max_height:
            first = midpoint + 1
        else:
            last = midpoint - 1
    return ly
Пример #7
0
 def test_context_get_metrics(self):
     # Test default "language" argument
     font_map = PangoCairo.font_map_get_default()
     context = font_map.create_context()
     desc = Pango.FontDescription('monospace')
     metrics1 = context.get_metrics(desc)
     metrics2 = context.get_metrics(desc, context.get_language())
     self.assertEqual(metrics1.get_ascent(), metrics2.get_ascent())
Пример #8
0
 def test_context_get_metrics(self):
     # Test default "language" argument
     font_map = PangoCairo.font_map_get_default()
     context = font_map.create_context()
     desc = Pango.FontDescription('monospace')
     metrics1 = context.get_metrics(desc)
     metrics2 = context.get_metrics(desc, context.get_language())
     self.assertEqual(metrics1.get_ascent(), metrics2.get_ascent())
Пример #9
0
 def __init__(self):
     """
     Populate the class variable __FONTS only once.
     """
     if SystemFonts.__FONTS is None:
         families = PangoCairo.font_map_get_default().list_families()
         #print ('GRAMPS GTK3: a g_value_get_object warning:')
         SystemFonts.__FONTS = [family.get_name() for family in families]
         SystemFonts.__FONTS.sort()
Пример #10
0
 def __init__(self):
     """
     Populate the class variable __FONTS only once.
     """
     if SystemFonts.__FONTS is None:
         families = PangoCairo.font_map_get_default().list_families()
         #print ('GRAMPS GTK3: a g_value_get_object warning:')
         SystemFonts.__FONTS = [family.get_name() for family in families]
         SystemFonts.__FONTS.sort()
Пример #11
0
def main():
    font_map = pangocairo.font_map_get_default()
    font_families = [family.get_name() for family in font_map.list_families()]
    if "CC Icons" not in font_families:
        raise Exception(
            "CC Icons font not installed. See <https://wiki.debian.org/Fonts>."
        )

    script_dir = os.path.dirname(__file__)
    basedir = os.path.realpath(
        os.path.abspath(os.path.join(script_dir, "..", "www", "i")))
    print("# basedir:", basedir)

    for suite, licenses in SUITES.items():
        for lic, module_chars in licenses.items():
            for chars, dimensions, background, foreground in product(
                    module_chars, DIMENSIONS, BACKGROUNDS, FOREGROUNDS):
                # e.g. white on white
                if foreground == background:
                    continue
                path = os.path.realpath(
                    os.path.abspath(
                        os.path.join(
                            basedir,
                            icon_path(suite, lic, background, foreground),
                        )))
                filepath = os.path.realpath(
                    os.path.abspath(
                        os.path.join(path, icon_filename(dimensions, chars))))
                if os.path.exists(filepath):
                    continue
                width = dimensions[0]
                height = dimensions[1]
                font_size = dimensions[2]
                padding = dimensions[3]
                ctx = genicon(
                    suite,
                    chars,
                    font_size,
                    padding,
                    width,
                    height,
                    background,
                    foreground,
                )
                try:
                    os.makedirs(path)
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        raise
                # Will raise and exception on error
                ctx.get_target().write_to_png(filepath)
Пример #12
0
def fontnames():
    """Returns a list of available Pango font names. Names are returned in the
    Pango font string format, e.g. "Inconsolata Bold"."""
    names = []
    families = PangoCairo.font_map_get_default().list_families()
    for family in families:
        # FIXME: Ensure this is the correct way to make a font name
        facenames = [
            f"{family.get_name()} {face.get_face_name()}"
            for face in family.list_faces()
        ]
        names.extend(facenames)
        # description = face.describe()
    return names
Пример #13
0
def list_pango_fonts():
    """Returns a list of available Pango font names. Names are returned in the
    Pango font string format, e.g. "Inconsolata Bold"."""
    names = []
    families = PangoCairo.font_map_get_default().list_families()
    for family in families:
        # in Inconsolata Bold, Inconsolata is the family, and Bold is the face
        facenames = [
            f"{family.get_name()} {face.get_face_name()}"
            for face in family.list_faces()
        ]
        names.extend(facenames)
        # this is how to access a font's FontDescription, which will help if
        # or when we want to get more info from font files
        # description = face.describe()
    return names
Пример #14
0
def get_font_desc(font_family, font_size, font_weight):
    font_map = PangoCairo.font_map_get_default()
    desc = next((
        v.list_faces()[0].describe() for v in font_map.list_families()
        if font_family.lower() in v.get_name().lower()
    ), None)  # TODO Default font

    if desc is None:
        return None

    desc.set_style(Pango.Style.NORMAL)
    desc.set_weight(Pango.Weight.NORMAL)

    if font_size is not None:
        desc.set_size(font_size * Pango.SCALE)

    if font_weight is not None:
        desc.set_weight(font_weight)

    return desc
Пример #15
0
def get_font(font, font_family, font_size, font_weight, font_stretch):
    """work around for Roboto Condensed not working on OS X"""
    desc = Pango.font_description_from_string(font)

    if font_family is not None:
        '''
        if ' condensed' in font_family:
            font_family = font_family.replace(' condensed', '')
            font_stretch = Pango.Stretch.EXPANDED
        elif ' Condensed' in font_family:
            font_family = font_family.replace(' Condensed', '')
            font_stretch = Pango.Stretch.EXPANDED
        '''

        font_map = PangoCairo.font_map_get_default()
        new_desc = next((v.list_faces()[0].describe()
                         for v in font_map.list_families()
                         if font_family.lower() in v.get_name().lower()), None)

        if new_desc:
            desc = new_desc
            desc.set_style(Pango.Style.NORMAL)
            desc.set_weight(Pango.Weight.NORMAL)
            desc.set_stretch(Pango.Stretch.NORMAL)
        else:
            print('"{}" font family not found. "{}" used as fallback.'.format(
                font_family, font))

    if font_size is not None:
        desc.set_size(font_size * Pango.SCALE * 0.72)

    if font_weight is not None:
        desc.set_weight(font_weight)

    if font_stretch is not None:
        desc.set_stretch(font_stretch)

    return desc
Пример #16
0
 def __init__(self,
              drawable,
              height,
              width,
              y,
              x,
              colour=ui.colour_default,
              monospace_font=None,
              font=None):
     # y and x are in pixels, height and width are in characters
     self.monospace = monospace_font
     self.font = font if font else monospace_font
     fontmap = PangoCairo.font_map_get_default()
     pangoctx = fontmap.create_context()
     metrics = pangoctx.get_metrics(self.monospace)
     self.fontwidth = metrics.get_approximate_digit_width() // Pango.SCALE
     self.ascent = metrics.get_ascent() // Pango.SCALE
     self.descent = metrics.get_descent() // Pango.SCALE
     self.fontheight = self.ascent + self.descent
     super().__init__(drawable, height * self.fontheight,
                      width * self.fontwidth, y, x)
     self.height_chars = height
     self.width_chars = width
     self.cur_y = 0
     self.cur_x = 0
     self.colour = colour
     self._cursor_on = True
     # XXX it should be possible to use a cairo.RecordingSurface
     # here to save memory on surfaces that will be written to on
     # initialisation and which will then be static, but this was
     # introduced in pycairo 1.11.0 and Ubuntu 16.04 to 17.10 only
     # have pycairo-1.10.0.  Ubuntu 18.04 has pycairo-1.16.0 so
     # implement it once all installations have been upgraded!
     self._surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width,
                                        self.height)
     self.erase()
Пример #17
0
_ = glocale.translation.gettext
from gi.repository import Gtk
from gi.repository import Pango, PangoCairo

#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from gramps.gen.plug.docgen import (BaseDoc, TextDoc, FONT_SERIF,
                                    PARA_ALIGN_RIGHT, FONT_SANS_SERIF,
                                    FONT_MONOSPACE, PARA_ALIGN_CENTER,
                                    PARA_ALIGN_LEFT)
from ...managedwindow import ManagedWindow

RESOLUTION = PangoCairo.font_map_get_default().get_resolution()


def pixels(cm):
    return int(RESOLUTION / 2.54 * cm)


#------------------------------------------------------------------------
#
# Constants
#
#------------------------------------------------------------------------
LEFT, RIGHT, CENTER = 'LEFT', 'RIGHT', 'CENTER'
_WIDTH_IN_CHARS = 72

Пример #18
0
    def use_pango_font(font, start, count, will_call_prepost=False):
        import gi
        gi.require_version('Pango', '1.0')
        gi.require_version('PangoCairo', '1.0')
        from gi.repository import Pango
        from gi.repository import PangoCairo
        #from gi.repository import Cairo as cairo
        import cairo

        fontDesc = Pango.FontDescription(font)
        a = array.array('b', itertools.repeat(0, 256 * 256))
        surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_A8, 256,
                                                     256)
        context = cairo.Context(surface)
        pango_context = PangoCairo.create_context(context)
        layout = PangoCairo.create_layout(context)
        fontmap = PangoCairo.font_map_get_default()
        font = fontmap.load_font(fontmap.create_context(), fontDesc)
        layout.set_font_description(fontDesc)
        metrics = font.get_metrics()
        descent = metrics.get_descent()
        d = descent / Pango.SCALE
        linespace = metrics.get_ascent() + metrics.get_descent()
        width = metrics.get_approximate_char_width()

        glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT)
        glPixelStorei(GL_UNPACK_SWAP_BYTES, 0)
        glPixelStorei(GL_UNPACK_LSB_FIRST, 1)
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 256)
        glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 256)
        glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0)
        glPixelStorei(GL_UNPACK_SKIP_ROWS, 0)
        glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glPixelZoom(1, -1)

        base = glGenLists(count)
        for i in range(count):
            ch = chr(start + i)
            layout.set_text(ch, -1)
            w, h = layout.get_size()
            context.save()
            context.new_path()
            context.rectangle(0, 0, 256, 256)
            context.set_source_rgba(0., 0., 0., 0.)
            context.set_operator(cairo.OPERATOR_SOURCE)
            context.paint()
            context.restore()

            context.save()
            context.set_source_rgba(1., 1., 1., 1.)
            context.set_operator(cairo.OPERATOR_SOURCE)
            context.move_to(0, 0)
            PangoCairo.update_context(context, pango_context)
            PangoCairo.show_layout(context, layout)
            context.restore()
            w, h = int(w / Pango.SCALE), int(h / Pango.SCALE)
            glNewList(base + i, GL_COMPILE)
            glBitmap(0, 0, 0, 0, 0, h - d, ''.encode())
            #glDrawPixels(0, 0, 0, 0, 0, h-d, '');
            if not will_call_prepost:
                pango_font_pre()
            if w and h:
                try:
                    pass
                    glDrawPixels(w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE,
                                 a.tostring())
                except Exception as e:
                    print("glnav Exception ", e)

            glBitmap(0, 0, 0, 0, w, -h + d, ''.encode())
            if not will_call_prepost:
                pango_font_post()
            glEndList()

        glPopClientAttrib()
        return base, int(width / Pango.SCALE), int(linespace / Pango.SCALE)
Пример #19
0
Файл: papr.py Проект: kspi/papr
def main():
    # SetUp OptionParser
    parser = argparse.ArgumentParser(description='Create a Calendar')

    parser.add_argument("-o", "--out", dest="out",
                        help="specify output file", default="out.pdf")

    parser.add_argument("-A", "--abbreviate_all", action="store_true",
                        help="use abbreviations for weekdays and months", default=False)

    parser.add_argument("-a", "--abbreviate", action="store_true",
                        help="use abbreviations for weekdays", default=False)

    parser.add_argument("-b", "--brand",
                        help="assign a brand string", default="")

    parser.add_argument("-c", "--color", action="store_true",
                        help="color date numbers", default=False)

    font_map = PangoCairo.font_map_get_default()
    parser.add_argument("-f", "--fonts", choices=[f.get_name(
    ) for f in font_map.list_families()], help="choose which font to use", default="Sans", metavar="FONT", nargs="+")

    parser.add_argument("-l", "--locale",
                        help="choose locale to use (default en_US.UTF8, check 'locale -a' for available locales)", default="en_US")

    # create date object to set default month and year to today
    td = datetime.date.today()
    parser.add_argument("-m", "--month", type=int, choices=range(1, 13), metavar="MONTH",
                        help="specify the starting month as a number (1-12), default is the current month (" + str(td.month) + ").", default=td.month)

    parser.add_argument("-y", "--year", type=int, choices=range(1990, datetime.MAXYEAR + 1), metavar="YEAR",
                        help="specify the year the calendar should start, default is the current year (" + str(td.year) + ").", default=td.year)

    # currently supported sizes of paper
    paperSizes = ("A5", "A4", "A3", "A2", "A1", "A0", "USLetter")
    parser.add_argument("-p", "--paper", choices=paperSizes,
                        help="choose which paper dimensions should be used " + str(paperSizes) + " default is A4", default="A4")

    parser.add_argument("--margin", type=int,
                        help="specify the margin of the calendar in millimeters. Used to adapt to your printer, default ist 5mm", default=5)

    parser.add_argument("-v", "--verbose", action="store_true",
                        help="print status messages to stdout", default=False)

    parser.add_argument("-d", "--debug", action="store_true",
                        help="print status and debug messages to stdout", default=False)
    layouts = ("classic", "column", 'oneyear')
    parser.add_argument("layout", choices=layouts, metavar="LAYOUT",
                        help="choose calendar layout: " + str(layouts))
    environment = parser.parse_args()

    # defining output
    if(environment.debug):
        logging.basicConfig(format='%(message)s', level=logging.DEBUG)
    elif(environment.verbose):
        logging.basicConfig(format='%(message)s', level=logging.INFO)

    # setting locale
    try:
        logging.debug("setting locale to '%s'", environment.locale)
        locale.setlocale(locale.LC_ALL, environment.locale)
    except locale.Error:
        logging.error(
            "locale: '%s' not found!\nList all installed locales with 'locale -a' and choose locale with -l/--locale option.", environment.locale)
        sys.exit(1)

    logging.debug(
        "Adjusting width and height values according to desired paper format: " + environment.paper)
    if environment.paper == "A5":
        environment.width = 14.8 * metrics.CM
        environment.height = 21.0 * metrics.CM
    elif environment.paper == "A4":
        environment.width = 21.0 * metrics.CM
        environment.height = 29.7 * metrics.CM
    elif environment.paper == "A3":
        environment.width = 29.7 * metrics.CM
        environment.height = 42.0 * metrics.CM
    elif environment.paper == "A2":
        environment.width = 42.0 * metrics.CM
        environment.height = 59.4 * metrics.CM
    elif environment.paper == "A1":
        environment.width = 59.4 * metrics.CM
        environment.height = 84.1 * metrics.CM
    elif environment.paper == "A0":
        environment.width = 84.1 * metrics.CM
        environment.height = 118.9 * metrics.CM
    elif environment.paper == "USLetter":
        environment.width = 8.5 * metrics.INCH
        environment.height = 11.0 * metrics.INCH


    # Setup fonts
    environment.font = environment.fonts.pop() # last provided font is used generally
    try:
        environment.fontHeading = environment.fonts.pop() # use additional provided font for headers
    except IndexError:
        environment.fontHeading = environment.font # if just one font set heading font same as general


    # env.safety margin for printing (A4 printers a unable to print on the
    # whole page)
    environment.safety = environment.margin * metrics.MM


    if (environment.debug):
        # Printing Options for Debugging
        dic = vars(environment)
        for key in dic:
            if(dic[key] != None):
                logging.debug("%s = %s", key, dic[key])

    drawCalendar = {"classic": classic.drawCalendar,
                    "column": column.drawCalendar,
                    "oneyear": oneyear.drawCalendar}
    drawCalendar[environment.layout](environment)

    return 0
Пример #20
0
font_properties_list = list(font_properties.items())

import random


def random_font():
    font, properties = random.choice(font_properties_list)
    style = random.randrange(4 if properties[BOLD] else 2)

    return font, properties[SIZE], style


if __name__ == '__main__':
    from gi.repository import PangoCairo

    font_map = PangoCairo.font_map_get_default()
    families = font_map.list_families()
    font_names = [f.get_name() for f in families]

    for f in sorted(font_names):
        if f in font_properties:
            print('\n{}{}'.format(f, font_properties[f]))
        else:
            print("[X]{}".format(f), end='\t')

    print()
    for f in sorted(font_properties.keys()):
        if f in font_names:
            print("[✓]{}".format(font_properties[f][ABBR]), end=' ')
        else:
            print("\n[!]{} NOT INSTALLED".format(f))
Пример #21
0
def get_fonts():
    font_map = pangocairo.font_map_get_default()
    font_families = [family.get_name() for family in font_map.list_families()]
    if "CC Icons" not in font_families:
        raise Exception("CC Icons font not installed. See"
                        " <https://wiki.debian.org/Fonts>.")
Пример #22
0
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gi.repository import Gtk
from gi.repository import Pango, PangoCairo

#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from gramps.gen.plug.docgen import (BaseDoc, TextDoc, FONT_SERIF, PARA_ALIGN_RIGHT,
                        FONT_SANS_SERIF, FONT_MONOSPACE, PARA_ALIGN_CENTER,
                        PARA_ALIGN_LEFT)
from ...managedwindow import ManagedWindow

RESOLUTION = PangoCairo.font_map_get_default().get_resolution()

def pixels(cm):
    return int (RESOLUTION/2.54 * cm)

#------------------------------------------------------------------------
#
# Constants
#
#------------------------------------------------------------------------
LEFT,RIGHT,CENTER = 'LEFT','RIGHT','CENTER'
_WIDTH_IN_CHARS = 72

class DisplayBuf(ManagedWindow):
    def __init__(self, title, document, track=[]):
        self.title = title
Пример #23
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.set_title(_("Titler"))
        self.connect("delete-event", lambda w, e:close_titler())
        
        if editorstate.screen_size_small_height() == True:
            global TEXT_LAYER_LIST_HEIGHT, TEXT_VIEW_HEIGHT, VIEW_EDITOR_HEIGHT
            TEXT_LAYER_LIST_HEIGHT = 150
            TEXT_VIEW_HEIGHT = 180
            VIEW_EDITOR_HEIGHT = 450

        if editorstate.screen_size_small_height() == True:
            global VIEW_EDITOR_WIDTH
            VIEW_EDITOR_WIDTH = 680
            
        self.block_updates = False
        
        self.view_editor = vieweditor.ViewEditor(PLAYER().profile, VIEW_EDITOR_WIDTH, VIEW_EDITOR_HEIGHT)
        self.view_editor.active_layer_changed_listener = self.active_layer_changed
        
        self.guides_toggle = vieweditor.GuidesViewToggle(self.view_editor)
        
        add_b = Gtk.Button(_("Add"))
        del_b = Gtk.Button(_("Delete"))
        add_b.connect("clicked", lambda w:self._add_layer_pressed())
        del_b.connect("clicked", lambda w:self._del_layer_pressed())
        add_del_box = Gtk.HBox()
        add_del_box = Gtk.HBox(True,1)
        add_del_box.pack_start(add_b, True, True, 0)
        add_del_box.pack_start(del_b, True, True, 0)

        center_h_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH + "center_horizontal.png")
        center_v_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH + "center_vertical.png")
        center_h = Gtk.Button()
        center_h.set_image(center_h_icon)
        center_h.connect("clicked", lambda w:self._center_h_pressed())
        center_v = Gtk.Button()
        center_v.set_image(center_v_icon)
        center_v.connect("clicked", lambda w:self._center_v_pressed())

        self.layer_list = TextLayerListView(self._layer_selection_changed, self._layer_visibility_toggled)
        self.layer_list.set_size_request(TEXT_LAYER_LIST_WIDTH, TEXT_LAYER_LIST_HEIGHT)
    
        self.text_view = Gtk.TextView()
        self.text_view.set_pixels_above_lines(2)
        self.text_view.set_left_margin(2)
        self.text_view.get_buffer().connect("changed", self._text_changed)

        self.sw = Gtk.ScrolledWindow()
        self.sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        self.sw.add(self.text_view)
        self.sw.set_size_request(TEXT_VIEW_WIDTH, TEXT_VIEW_HEIGHT)

        scroll_frame = Gtk.Frame()
        scroll_frame.add(self.sw)
        
        self.tc_display = guicomponents.MonitorTCDisplay()
        self.tc_display.use_internal_frame = True
        self.tc_display.widget.set_valign(Gtk.Align.CENTER)
        
        self.pos_bar = positionbar.PositionBar()
        self.pos_bar.set_listener(self.position_listener)
        self.pos_bar.update_display_from_producer(PLAYER().producer)
        self.pos_bar.mouse_release_listener = self.pos_bar_mouse_released

        pos_bar_frame = Gtk.Frame()
        pos_bar_frame.add(self.pos_bar.widget)
        pos_bar_frame.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        pos_bar_frame.set_valign(Gtk.Align.CENTER)
                
        font_map = PangoCairo.font_map_get_default()
        unsorted_families = font_map.list_families()
        if len(unsorted_families) == 0:
            print "No font families found in system! Titler will not work."
        self.font_families = sorted(unsorted_families, key=lambda family: family.get_name())
        self.font_family_indexes_for_name = {}
        combo = Gtk.ComboBoxText()
        indx = 0
        for family in self.font_families:
            combo.append_text(family.get_name())
            self.font_family_indexes_for_name[family.get_name()] = indx
            indx += 1
        combo.set_active(0)
        self.font_select = combo
        self.font_select.connect("changed", self._edit_value_changed)
    
        adj = Gtk.Adjustment(float(DEFAULT_FONT_SIZE), float(1), float(300), float(1))
        self.size_spin = Gtk.SpinButton()
        self.size_spin.set_adjustment(adj)
        self.size_spin.connect("changed", self._edit_value_changed)
        self.size_spin.connect("key-press-event", self._key_pressed_on_widget)

        font_main_row = Gtk.HBox()
        font_main_row.pack_start(self.font_select, True, True, 0)
        font_main_row.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        font_main_row.pack_start(self.size_spin, False, False, 0)

        self.bold_font = Gtk.ToggleButton()
        self.italic_font = Gtk.ToggleButton()
        bold_icon = Gtk.Image.new_from_stock(Gtk.STOCK_BOLD, 
                                       Gtk.IconSize.BUTTON)
        italic_icon = Gtk.Image.new_from_stock(Gtk.STOCK_ITALIC, 
                                       Gtk.IconSize.BUTTON)
        self.bold_font.set_image(bold_icon)
        self.italic_font.set_image(italic_icon)
        self.bold_font.connect("clicked", self._edit_value_changed)
        self.italic_font.connect("clicked", self._edit_value_changed)
        
        self.left_align = Gtk.RadioButton(None)
        self.center_align = Gtk.RadioButton.new_from_widget(self.left_align)
        self.right_align = Gtk.RadioButton.new_from_widget(self.left_align)
        left_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_LEFT, 
                                       Gtk.IconSize.BUTTON)
        center_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_CENTER, 
                                       Gtk.IconSize.BUTTON)
        right_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_RIGHT, 
                                       Gtk.IconSize.BUTTON)
        self.left_align.set_image(left_icon)
        self.center_align.set_image(center_icon)
        self.right_align.set_image(right_icon)
        self.left_align.set_mode(False)
        self.center_align.set_mode(False)
        self.right_align.set_mode(False)
        self.left_align.connect("clicked", self._edit_value_changed)
        self.center_align.connect("clicked", self._edit_value_changed)
        self.right_align.connect("clicked", self._edit_value_changed)
        
        self.color_button = Gtk.ColorButton.new_with_rgba(Gdk.RGBA(red=1.0, green=1.0, blue=1.0, alpha=1.0))
        self.color_button.connect("color-set", self._edit_value_changed)

        buttons_box = Gtk.HBox()
        buttons_box.pack_start(Gtk.Label(), True, True, 0)
        buttons_box.pack_start(self.bold_font, False, False, 0)
        buttons_box.pack_start(self.italic_font, False, False, 0)
        buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        buttons_box.pack_start(self.left_align, False, False, 0)
        buttons_box.pack_start(self.center_align, False, False, 0)
        buttons_box.pack_start(self.right_align, False, False, 0)
        buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        buttons_box.pack_start(self.color_button, False, False, 0)
        buttons_box.pack_start(Gtk.Label(), True, True, 0)

        load_layers = Gtk.Button(_("Load Layers"))
        load_layers.connect("clicked", lambda w:self._load_layers_pressed())
        save_layers = Gtk.Button(_("Save Layers"))
        save_layers.connect("clicked", lambda w:self._save_layers_pressed())
        clear_layers = Gtk.Button(_("Clear All"))
        clear_layers.connect("clicked", lambda w:self._clear_layers_pressed())

        layers_save_buttons_row = Gtk.HBox()
        layers_save_buttons_row.pack_start(save_layers, False, False, 0)
        layers_save_buttons_row.pack_start(load_layers, False, False, 0)
        layers_save_buttons_row.pack_start(Gtk.Label(), True, True, 0)
        
        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.x_pos_spin = Gtk.SpinButton()
        self.x_pos_spin.set_adjustment(adj)
        self.x_pos_spin.connect("changed", self._position_value_changed)
        self.x_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.y_pos_spin = Gtk.SpinButton()
        self.y_pos_spin.set_adjustment(adj)
        self.y_pos_spin.connect("changed", self._position_value_changed)
        self.y_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.rotation_spin = Gtk.SpinButton()
        self.rotation_spin.set_adjustment(adj)
        self.rotation_spin.connect("changed", self._position_value_changed)
        self.rotation_spin.connect("key-press-event", self._key_pressed_on_widget)
        
        undo_pos = Gtk.Button()
        undo_icon = Gtk.Image.new_from_stock(Gtk.STOCK_UNDO, 
                                       Gtk.IconSize.BUTTON)
        undo_pos.set_image(undo_icon)

        next_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH + "next_frame_s.png")
        prev_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH + "prev_frame_s.png")
        prev_frame = Gtk.Button()
        prev_frame.set_image(prev_icon)
        prev_frame.connect("clicked", lambda w:self._prev_frame_pressed())
        next_frame = Gtk.Button()
        next_frame.set_image(next_icon)
        next_frame.connect("clicked", lambda w:self._next_frame_pressed())

        self.scale_selector = vieweditor.ScaleSelector(self)

        timeline_box = Gtk.HBox()
        timeline_box.pack_start(self.tc_display.widget, False, False, 0)
        timeline_box.pack_start(guiutils.pad_label(12, 12), False, False, 0)
        timeline_box.pack_start(pos_bar_frame, True, True, 0)
        timeline_box.pack_start(guiutils.pad_label(12, 12), False, False, 0)
        timeline_box.pack_start(prev_frame, False, False, 0)
        timeline_box.pack_start(next_frame, False, False, 0)
        timeline_box.pack_start(self.guides_toggle, False, False, 0)
        timeline_box.pack_start(self.scale_selector, False, False, 0)
        timeline_box.set_margin_top(6)
        timeline_box.set_margin_bottom(6)
        
        positions_box = Gtk.HBox()
        positions_box.pack_start(Gtk.Label(), True, True, 0)
        positions_box.pack_start(Gtk.Label(label="X:"), False, False, 0)
        positions_box.pack_start(self.x_pos_spin, False, False, 0)
        positions_box.pack_start(guiutils.pad_label(40, 5), False, False, 0)
        positions_box.pack_start(Gtk.Label(label="Y:"), False, False, 0)
        positions_box.pack_start(self.y_pos_spin, False, False, 0)
        #positions_box.pack_start(Gtk.Label(label=_("Angle")), False, False, 0)
        #positions_box.pack_start(self.rotation_spin, False, False, 0)
        positions_box.pack_start(guiutils.pad_label(40, 5), False, False, 0)
        positions_box.pack_start(center_h, False, False, 0)
        positions_box.pack_start(center_v, False, False, 0)
        positions_box.pack_start(Gtk.Label(), True, True, 0)

        controls_panel_1 = Gtk.VBox()
        controls_panel_1.pack_start(add_del_box, False, False, 0)
        controls_panel_1.pack_start(self.layer_list, False, False, 0)
        controls_panel_1.pack_start(layers_save_buttons_row, False, False, 0)

        controls_panel_2 = Gtk.VBox()
        controls_panel_2.pack_start(scroll_frame, True, True, 0)
        controls_panel_2.pack_start(font_main_row, False, False, 0)
        controls_panel_2.pack_start(buttons_box, False, False, 0)
        
        controls_panel = Gtk.VBox()
        controls_panel.pack_start(guiutils.get_named_frame(_("Active Layer"),controls_panel_2), True, True, 0)
        controls_panel.pack_start(guiutils.get_named_frame(_("Layers"),controls_panel_1), False, False, 0)
 
        view_editor_editor_buttons_row = Gtk.HBox()
        view_editor_editor_buttons_row.pack_start(positions_box, False, False, 0)
        view_editor_editor_buttons_row.pack_start(Gtk.Label(), True, True, 0)

        keep_label = Gtk.Label(label=_("Keep Layers When Closed"))
        self.keep_layers_check = Gtk.CheckButton()
        self.keep_layers_check.set_active(_keep_titler_data)
        self.keep_layers_check.connect("toggled", self._keep_layers_toggled)
        
        open_label = Gtk.Label(label=_("Open Saved Title In Bin"))
        self.open_in_current_check = Gtk.CheckButton()
        self.open_in_current_check.set_active(_open_saved_in_bin)
        self.open_in_current_check.connect("toggled", self._open_saved_in_bin)

        exit_b = guiutils.get_sized_button(_("Close"), 150, 32)
        exit_b.connect("clicked", lambda w:close_titler())
        save_titles_b = guiutils.get_sized_button(_("Save Title Graphic"), 150, 32)
        save_titles_b.connect("clicked", lambda w:self._save_title_pressed())
        
        editor_buttons_row = Gtk.HBox()
        editor_buttons_row.pack_start(Gtk.Label(), True, True, 0)
        editor_buttons_row.pack_start(keep_label, False, False, 0)
        editor_buttons_row.pack_start(self.keep_layers_check, False, False, 0)
        editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0)
        editor_buttons_row.pack_start(open_label, False, False, 0)
        editor_buttons_row.pack_start(self.open_in_current_check, False, False, 0)
        editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False, 0)
        editor_buttons_row.pack_start(exit_b, False, False, 0)
        editor_buttons_row.pack_start(save_titles_b, False, False, 0)
        
        editor_panel = Gtk.VBox()
        editor_panel.pack_start(self.view_editor, True, True, 0)
        editor_panel.pack_start(timeline_box, False, False, 0)
        editor_panel.pack_start(guiutils.get_in_centering_alignment(view_editor_editor_buttons_row), False, False, 0)
        editor_panel.pack_start(guiutils.pad_label(2, 24), True, True, 0)
        editor_panel.pack_start(editor_buttons_row, False, False, 0)

        editor_row = Gtk.HBox()
        editor_row.pack_start(controls_panel, False, False, 0)
        editor_row.pack_start(editor_panel, True, True, 0)

        alignment = guiutils.set_margins(editor_row, 8,8,8,8)

        self.add(alignment)

        self.layer_list.fill_data_model()
        self._update_gui_with_active_layer_data()
        self.show_all()

        self.connect("size-allocate", lambda w, e:self.window_resized())
        self.connect("window-state-event", lambda w, e:self.window_resized())
def _get_screen_dpi():
    xft_dpi = Gtk.Settings.get_default().get_property('gtk-xft-dpi')
    dpi = float(xft_dpi / 1024)
    logging.debug('Setting dpi to: %f', dpi)
    # HACK: if the DPI detected is 200.0 it seems we are on an XO, so
    # we return 133 because the XO manage its resolution in a complex
    # way. More information here:
    #     http://wiki.laptop.org/go/Display
    if 200 == int(dpi):
        return 133
    return dpi


dpi = _get_screen_dpi()
font_map_default = PangoCairo.font_map_get_default()
font_map_default.set_resolution(dpi)

# Import activity modules.
import mainscreen, editlessonlistscreen


# This is the main Typing Turtle activity class.
#
# It owns the main application window, and all the various toolbars and options.
# Activity Screens are stored in a stack, with the currently active screen on top.
class TypingTurtle(sugar3.activity.activity.Activity):
    def __init__(self, handle):
        sugar3.activity.activity.Activity.__init__(self, handle)
        self.set_title(_("Typing Turtle"))
        self.max_participants = 1
Пример #25
0
def _set_screen_dpi():
    dpi = _get_screen_dpi()
    font_map_default = PangoCairo.font_map_get_default()
    font_map_default.set_resolution(dpi)
Пример #26
0
	def draw_customize_box(self, draw_type):
		self.CBox = Gtk.Box()

		if not hasattr(self, 'LwAdj'):
			self.LwAdj = 20
		if not hasattr(self, 'img_alpha'):
			self.img_alpha = 100

		self.ClSelBtn = Gtk.EventBox()
		self.ClSelBtn.set_tooltip_text('change the color')
		self.ClSelLabel = Gtk.Label('           ')
		self.ClSelBtn.add(self.ClSelLabel)
		self.ClSelBtn.connect('button-press-event', self.on_color_chooser, draw_type)

		self.SetLw = Gtk.Entry()
		self.SetLw.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(.95, .95, .95))
		self.SetLw.set_has_frame(False)
		self.SetLw.set_width_chars(3)

		if draw_type == 'text':
			self.LwAdj = 20
		self.SetLw.set_text(str(self.LwAdj))

		#GTK HAXX FTW!
		def focus_loss(spinner):
			spinner.set_state(Gtk.StateType.INSENSITIVE)
			spinner.set_state(Gtk.StateType.NORMAL)

		self.SetLw.connect('changed', self.spin_chk, self.SetLw)
		self.SetLw.connect('activate', focus_loss)

		self.CBox.pack_start(self.ClSelBtn, False, False, 20)

		for n, c in reversed(sorted(dics.tool_cfg_ui.items())):
			self.make_btn(c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10])

		self.CBox.pack_start(self.SetLw, False, False, 20)

		if draw_type == 'line':
			self.FillIBox.destroy()

		if draw_type == 'img':
			self.ClSelBtn.destroy()
			self.SetLw.destroy()
			self.LCIBox.destroy()
			self.FillIBox.destroy()

			self.img_slider_container = Gtk.Box()
			self.img_slider = Gtk.Entry()
			self.img_slider.set_has_frame(False)
			self.img_slider.set_width_chars(3)
			self.img_slider.set_text(str(self.img_alpha))
			self.img_slider.connect('changed', self.spin_chk, self.img_slider)

			self.img_slider_container.pack_start(self.img_slider, False, False, 0)
			self.CBox.pack_start(self.img_slider_container, False, False, 20)

		elif hasattr(self, 'img_slider'):
			self.img_slider.destroy()

		if draw_type == 'text':
			self.FillIBox.destroy()
			self.LCIBox.destroy()
			if hasattr(self, 'ClSel'):
				color = self.ClSel.get_current_color()
			else:
				color = Gdk.Color(dset.Cl[0], dset.Cl[1], dset.Cl[2])
			color = color.to_string()
			self.ClSelLabel.set_markup("<span font_desc=\"Sans Bold 20.0\" color=\"" + color + "\">  A  </span>")

			font_map = PangoCairo.font_map_get_default()
			fonts = [f.get_name() for f in font_map.list_families()]

			self.font_set = Gtk.ComboBoxText()
			self.font_set.set_entry_text_column(0)
			self.font_set.connect('changed', self.font_change)
			for font in fonts:
				self.font_set.append_text(font)
			self.font_set.set_active(0)
			self.font_set.set_focus_on_click(False)
			self.CBox.pack_start(self.font_set, False, False, 20)

		else:
			self.ClSelBtn.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(dset.Cl[0], dset.Cl[1], dset.Cl[2], dset.Cl[3]))
			self.ClSelBtn.override_background_color(Gtk.StateFlags.ACTIVE, Gdk.RGBA(dset.Cl[0], dset.Cl[1], dset.Cl[2], dset.Cl[3]))
			self.ClSelBtn.override_background_color(Gtk.StateFlags.SELECTED, Gdk.RGBA(dset.Cl[0], dset.Cl[1], dset.Cl[2], dset.Cl[3]))

		self.DrawBox.pack_end(self.CBox, False, False, 20)

		self.show_all()
Пример #27
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.set_title(_("Titler"))
        self.connect("delete-event", lambda w, e: close_titler())

        if editorstate.screen_size_small_height() == True:
            global TEXT_LAYER_LIST_HEIGHT, TEXT_VIEW_HEIGHT, VIEW_EDITOR_HEIGHT
            TEXT_LAYER_LIST_HEIGHT = 150
            TEXT_VIEW_HEIGHT = 180
            VIEW_EDITOR_HEIGHT = 450

        if editorstate.screen_size_small_height() == True:
            global VIEW_EDITOR_WIDTH
            VIEW_EDITOR_WIDTH = 680

        self.block_updates = False

        self.view_editor = vieweditor.ViewEditor(PLAYER().profile,
                                                 VIEW_EDITOR_WIDTH,
                                                 VIEW_EDITOR_HEIGHT)
        self.view_editor.active_layer_changed_listener = self.active_layer_changed

        self.guides_toggle = vieweditor.GuidesViewToggle(self.view_editor)

        add_b = Gtk.Button(_("Add"))
        del_b = Gtk.Button(_("Delete"))
        add_b.connect("clicked", lambda w: self._add_layer_pressed())
        del_b.connect("clicked", lambda w: self._del_layer_pressed())
        add_del_box = Gtk.HBox()
        add_del_box = Gtk.HBox(True, 1)
        add_del_box.pack_start(add_b, True, True, 0)
        add_del_box.pack_start(del_b, True, True, 0)

        center_h_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH +
                                                "center_horizontal.png")
        center_v_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH +
                                                "center_vertical.png")
        center_h = Gtk.Button()
        center_h.set_image(center_h_icon)
        center_h.connect("clicked", lambda w: self._center_h_pressed())
        center_v = Gtk.Button()
        center_v.set_image(center_v_icon)
        center_v.connect("clicked", lambda w: self._center_v_pressed())

        self.layer_list = TextLayerListView(self._layer_selection_changed,
                                            self._layer_visibility_toggled)
        self.layer_list.set_size_request(TEXT_LAYER_LIST_WIDTH,
                                         TEXT_LAYER_LIST_HEIGHT)

        self.text_view = Gtk.TextView()
        self.text_view.set_pixels_above_lines(2)
        self.text_view.set_left_margin(2)
        self.text_view.get_buffer().connect("changed", self._text_changed)

        self.sw = Gtk.ScrolledWindow()
        self.sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
        self.sw.add(self.text_view)
        self.sw.set_size_request(TEXT_VIEW_WIDTH, TEXT_VIEW_HEIGHT)

        scroll_frame = Gtk.Frame()
        scroll_frame.add(self.sw)

        self.tc_display = guicomponents.MonitorTCDisplay()
        self.tc_display.use_internal_frame = True
        self.tc_display.widget.set_valign(Gtk.Align.CENTER)

        self.pos_bar = positionbar.PositionBar()
        self.pos_bar.set_listener(self.position_listener)
        self.pos_bar.update_display_from_producer(PLAYER().producer)
        self.pos_bar.mouse_release_listener = self.pos_bar_mouse_released

        pos_bar_frame = Gtk.Frame()
        pos_bar_frame.add(self.pos_bar.widget)
        pos_bar_frame.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
        pos_bar_frame.set_valign(Gtk.Align.CENTER)

        font_map = PangoCairo.font_map_get_default()
        unsorted_families = font_map.list_families()
        if len(unsorted_families) == 0:
            print "No font families found in system! Titler will not work."
        self.font_families = sorted(unsorted_families,
                                    key=lambda family: family.get_name())
        self.font_family_indexes_for_name = {}
        combo = Gtk.ComboBoxText()
        indx = 0
        for family in self.font_families:
            combo.append_text(family.get_name())
            self.font_family_indexes_for_name[family.get_name()] = indx
            indx += 1
        combo.set_active(0)
        self.font_select = combo
        self.font_select.connect("changed", self._edit_value_changed)

        adj = Gtk.Adjustment(float(DEFAULT_FONT_SIZE), float(1), float(300),
                             float(1))
        self.size_spin = Gtk.SpinButton()
        self.size_spin.set_adjustment(adj)
        self.size_spin.connect("changed", self._edit_value_changed)
        self.size_spin.connect("key-press-event", self._key_pressed_on_widget)

        font_main_row = Gtk.HBox()
        font_main_row.pack_start(self.font_select, True, True, 0)
        font_main_row.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        font_main_row.pack_start(self.size_spin, False, False, 0)

        self.bold_font = Gtk.ToggleButton()
        self.italic_font = Gtk.ToggleButton()
        bold_icon = Gtk.Image.new_from_stock(Gtk.STOCK_BOLD,
                                             Gtk.IconSize.BUTTON)
        italic_icon = Gtk.Image.new_from_stock(Gtk.STOCK_ITALIC,
                                               Gtk.IconSize.BUTTON)
        self.bold_font.set_image(bold_icon)
        self.italic_font.set_image(italic_icon)
        self.bold_font.connect("clicked", self._edit_value_changed)
        self.italic_font.connect("clicked", self._edit_value_changed)

        self.left_align = Gtk.RadioButton(None)
        self.center_align = Gtk.RadioButton.new_from_widget(self.left_align)
        self.right_align = Gtk.RadioButton.new_from_widget(self.left_align)
        left_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_LEFT,
                                             Gtk.IconSize.BUTTON)
        center_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_CENTER,
                                               Gtk.IconSize.BUTTON)
        right_icon = Gtk.Image.new_from_stock(Gtk.STOCK_JUSTIFY_RIGHT,
                                              Gtk.IconSize.BUTTON)
        self.left_align.set_image(left_icon)
        self.center_align.set_image(center_icon)
        self.right_align.set_image(right_icon)
        self.left_align.set_mode(False)
        self.center_align.set_mode(False)
        self.right_align.set_mode(False)
        self.left_align.connect("clicked", self._edit_value_changed)
        self.center_align.connect("clicked", self._edit_value_changed)
        self.right_align.connect("clicked", self._edit_value_changed)

        self.color_button = Gtk.ColorButton.new_with_rgba(
            Gdk.RGBA(red=1.0, green=1.0, blue=1.0, alpha=1.0))
        self.color_button.connect("color-set", self._edit_value_changed)

        buttons_box = Gtk.HBox()
        buttons_box.pack_start(Gtk.Label(), True, True, 0)
        buttons_box.pack_start(self.bold_font, False, False, 0)
        buttons_box.pack_start(self.italic_font, False, False, 0)
        buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        buttons_box.pack_start(self.left_align, False, False, 0)
        buttons_box.pack_start(self.center_align, False, False, 0)
        buttons_box.pack_start(self.right_align, False, False, 0)
        buttons_box.pack_start(guiutils.pad_label(5, 5), False, False, 0)
        buttons_box.pack_start(self.color_button, False, False, 0)
        buttons_box.pack_start(Gtk.Label(), True, True, 0)

        load_layers = Gtk.Button(_("Load Layers"))
        load_layers.connect("clicked", lambda w: self._load_layers_pressed())
        save_layers = Gtk.Button(_("Save Layers"))
        save_layers.connect("clicked", lambda w: self._save_layers_pressed())
        clear_layers = Gtk.Button(_("Clear All"))
        clear_layers.connect("clicked", lambda w: self._clear_layers_pressed())

        layers_save_buttons_row = Gtk.HBox()
        layers_save_buttons_row.pack_start(save_layers, False, False, 0)
        layers_save_buttons_row.pack_start(load_layers, False, False, 0)
        layers_save_buttons_row.pack_start(Gtk.Label(), True, True, 0)

        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.x_pos_spin = Gtk.SpinButton()
        self.x_pos_spin.set_adjustment(adj)
        self.x_pos_spin.connect("changed", self._position_value_changed)
        self.x_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.y_pos_spin = Gtk.SpinButton()
        self.y_pos_spin.set_adjustment(adj)
        self.y_pos_spin.connect("changed", self._position_value_changed)
        self.y_pos_spin.connect("key-press-event", self._key_pressed_on_widget)
        adj = Gtk.Adjustment(float(0), float(0), float(3000), float(1))
        self.rotation_spin = Gtk.SpinButton()
        self.rotation_spin.set_adjustment(adj)
        self.rotation_spin.connect("changed", self._position_value_changed)
        self.rotation_spin.connect("key-press-event",
                                   self._key_pressed_on_widget)

        undo_pos = Gtk.Button()
        undo_icon = Gtk.Image.new_from_stock(Gtk.STOCK_UNDO,
                                             Gtk.IconSize.BUTTON)
        undo_pos.set_image(undo_icon)

        next_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH +
                                            "next_frame_s.png")
        prev_icon = Gtk.Image.new_from_file(respaths.IMAGE_PATH +
                                            "prev_frame_s.png")
        prev_frame = Gtk.Button()
        prev_frame.set_image(prev_icon)
        prev_frame.connect("clicked", lambda w: self._prev_frame_pressed())
        next_frame = Gtk.Button()
        next_frame.set_image(next_icon)
        next_frame.connect("clicked", lambda w: self._next_frame_pressed())

        self.scale_selector = vieweditor.ScaleSelector(self)

        timeline_box = Gtk.HBox()
        timeline_box.pack_start(self.tc_display.widget, False, False, 0)
        timeline_box.pack_start(guiutils.pad_label(12, 12), False, False, 0)
        timeline_box.pack_start(pos_bar_frame, True, True, 0)
        timeline_box.pack_start(guiutils.pad_label(12, 12), False, False, 0)
        timeline_box.pack_start(prev_frame, False, False, 0)
        timeline_box.pack_start(next_frame, False, False, 0)
        timeline_box.pack_start(self.guides_toggle, False, False, 0)
        timeline_box.pack_start(self.scale_selector, False, False, 0)
        timeline_box.set_margin_top(6)
        timeline_box.set_margin_bottom(6)

        positions_box = Gtk.HBox()
        positions_box.pack_start(Gtk.Label(), True, True, 0)
        positions_box.pack_start(Gtk.Label(label="X:"), False, False, 0)
        positions_box.pack_start(self.x_pos_spin, False, False, 0)
        positions_box.pack_start(guiutils.pad_label(40, 5), False, False, 0)
        positions_box.pack_start(Gtk.Label(label="Y:"), False, False, 0)
        positions_box.pack_start(self.y_pos_spin, False, False, 0)
        #positions_box.pack_start(Gtk.Label(label=_("Angle")), False, False, 0)
        #positions_box.pack_start(self.rotation_spin, False, False, 0)
        positions_box.pack_start(guiutils.pad_label(40, 5), False, False, 0)
        positions_box.pack_start(center_h, False, False, 0)
        positions_box.pack_start(center_v, False, False, 0)
        positions_box.pack_start(Gtk.Label(), True, True, 0)

        controls_panel_1 = Gtk.VBox()
        controls_panel_1.pack_start(add_del_box, False, False, 0)
        controls_panel_1.pack_start(self.layer_list, False, False, 0)
        controls_panel_1.pack_start(layers_save_buttons_row, False, False, 0)

        controls_panel_2 = Gtk.VBox()
        controls_panel_2.pack_start(scroll_frame, True, True, 0)
        controls_panel_2.pack_start(font_main_row, False, False, 0)
        controls_panel_2.pack_start(buttons_box, False, False, 0)

        controls_panel = Gtk.VBox()
        controls_panel.pack_start(
            guiutils.get_named_frame(_("Active Layer"), controls_panel_2),
            True, True, 0)
        controls_panel.pack_start(
            guiutils.get_named_frame(_("Layers"), controls_panel_1), False,
            False, 0)

        view_editor_editor_buttons_row = Gtk.HBox()
        view_editor_editor_buttons_row.pack_start(positions_box, False, False,
                                                  0)
        view_editor_editor_buttons_row.pack_start(Gtk.Label(), True, True, 0)

        keep_label = Gtk.Label(label=_("Keep Layers When Closed"))
        self.keep_layers_check = Gtk.CheckButton()
        self.keep_layers_check.set_active(_keep_titler_data)
        self.keep_layers_check.connect("toggled", self._keep_layers_toggled)

        open_label = Gtk.Label(label=_("Open Saved Title In Bin"))
        self.open_in_current_check = Gtk.CheckButton()
        self.open_in_current_check.set_active(_open_saved_in_bin)
        self.open_in_current_check.connect("toggled", self._open_saved_in_bin)

        exit_b = guiutils.get_sized_button(_("Close"), 150, 32)
        exit_b.connect("clicked", lambda w: close_titler())
        save_titles_b = guiutils.get_sized_button(_("Save Title Graphic"), 150,
                                                  32)
        save_titles_b.connect("clicked", lambda w: self._save_title_pressed())

        editor_buttons_row = Gtk.HBox()
        editor_buttons_row.pack_start(Gtk.Label(), True, True, 0)
        editor_buttons_row.pack_start(keep_label, False, False, 0)
        editor_buttons_row.pack_start(self.keep_layers_check, False, False, 0)
        editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False,
                                      0)
        editor_buttons_row.pack_start(open_label, False, False, 0)
        editor_buttons_row.pack_start(self.open_in_current_check, False, False,
                                      0)
        editor_buttons_row.pack_start(guiutils.pad_label(24, 2), False, False,
                                      0)
        editor_buttons_row.pack_start(exit_b, False, False, 0)
        editor_buttons_row.pack_start(save_titles_b, False, False, 0)

        editor_panel = Gtk.VBox()
        editor_panel.pack_start(self.view_editor, True, True, 0)
        editor_panel.pack_start(timeline_box, False, False, 0)
        editor_panel.pack_start(
            guiutils.get_in_centering_alignment(
                view_editor_editor_buttons_row), False, False, 0)
        editor_panel.pack_start(guiutils.pad_label(2, 24), True, True, 0)
        editor_panel.pack_start(editor_buttons_row, False, False, 0)

        editor_row = Gtk.HBox()
        editor_row.pack_start(controls_panel, False, False, 0)
        editor_row.pack_start(editor_panel, True, True, 0)

        alignment = guiutils.set_margins(editor_row, 8, 8, 8, 8)

        self.add(alignment)

        self.layer_list.fill_data_model()
        self._update_gui_with_active_layer_data()
        self.show_all()

        self.connect("size-allocate", lambda w, e: self.window_resized())
        self.connect("window-state-event", lambda w, e: self.window_resized())
Пример #28
0
def _set_screen_dpi():
    dpi = _get_screen_dpi()
    font_map_default = PangoCairo.font_map_get_default()
    font_map_default.set_resolution(dpi)
Пример #29
0
    characters,
    font_size,
    padding,
    width,
    height,
    background,
    foreground,
):
    ctx = create_context(width, height)
    set_background(ctx, background, width, height)
    configure_font(ctx, font_size)
    show_chars(ctx, characters, foreground, padding, width, height)
    return ctx


font_map = pangocairo.font_map_get_default()
font_families = [family.get_name() for family in font_map.list_families()]
if "CC Icons" not in font_families:
    raise Exception("CC Icons font not installed. See"
                    " <https://wiki.debian.org/Fonts>.")

script_dir = os.path.dirname(__file__)
basedir = os.path.realpath(
    os.path.abspath(os.path.join(script_dir, "..", "www", "i")))
print("# basedir:", basedir)

for suite, licenses in SUITES.items():
    for lic, module_chars in licenses.items():
        for chars, dimensions, background, foreground in product(
                module_chars, DIMENSIONS, BACKGROUNDS, FOREGROUNDS):
            # e.g. white on white