Using PangoCairo with PyGObject API - python

I am porting a Python2 script that uses Pango for drawing text to a Cairo surface. It works fine using the old PyGtk API with the pangocairo package. My system (Debian Jesse) doesn't have Python3 packages for PyGtk and instead uses the newer Gtk+ libraries with the PyGObject API.
I want to create a pangocairo.CairoContext object but it seems to be missing in the new API. The PangoCairo package has a create_context() function but it generates a PangoContext object that doesn't have the methods I need.
So far I have this:
import cairo
from gi.repository import Pango
from gi.repository import PangoCairo
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
pctx = PangoCairo.create_context(ctx) # Creates a PangoContext
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) # This fails
The old Python2 code that works:
import cairo
import pango
import pangocairo
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
pctx = pangocairo.CairoContext(ctx)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
Does anyone have a solution for this? Is there any good documentation on how PangoCairo should be used with the new API?

It looks like the library has been rearranged a bit. The Pango context (now Pango.Context) is retrieved from the Pango.Layout object now. Here is a working solution:
import cairo
from gi.repository import Pango
from gi.repository import PangoCairo
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
layout = PangoCairo.create_layout(ctx)
pctx = layout.get_context()
fo = cairo.FontOptions()
fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
PangoCairo.context_set_font_options(pctx, fo)

Related

How to read url on active tab of browser

I am using python 2.7 but am not able to get anything how to read url which are active in tab of browsers.
So far i tried this
import win32gui
import win32process
import psutil
#w=win32gui
#value=w.GetWindowText(w.GetForegroundWindow())
#print(value)
appwindow = win32gui.GetForegroundWindow()
ProcessID = win32process.GetWindowThreadProcessId(appwindow)
#procname = psutil.Process(ProcessID)
#applicname = procname.name()
print("hello")
Check out pybrinf package, is Windows supported and allows you to get some info about a browser.

Python3 how to install .ttf font file?

I wanted to install .ttf font file on windows 10 with python3 (more precise Python 3.6) code, I googled but the only thing I found was this one Install TTF fonts on windows with python, I tested it but it didn't do anything. Is there a way to install .ttf with python3 code?
Thanks in advance.
This library seems promising (I haven't tried myself).
Installing
pip install --user fonttools
or
pip3 install --user fonttools
Code
from fontTools.ttLib import TTFont
font = TTFont('/path/to/font.ttf')
Then use font.save method:
Definition: font.save(self, file, reorderTables=True)
Docstring: Save
the font to disk. Similarly to the constructor, the 'file' argument
can be either a pathname or a writable file object.
This might help you, it tries to install all fonts in a folder but you can modify it to install 1 font only with the install_font function: https://gist.github.com/tushortz/598bf0324e37033ed870c4e46461fb1e
import os
import shutil
import ctypes
from ctypes import wintypes
import sys
import ntpath
try:
import winreg
except ImportError:
import _winreg as winreg
user32 = ctypes.WinDLL('user32', use_last_error=True)
gdi32 = ctypes.WinDLL('gdi32', use_last_error=True)
FONTS_REG_PATH = r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'
HWND_BROADCAST = 0xFFFF
SMTO_ABORTIFHUNG = 0x0002
WM_FONTCHANGE = 0x001D
GFRI_DESCRIPTION = 1
GFRI_ISTRUETYPE = 3
def install_font(src_path):
# copy the font to the Windows Fonts folder
dst_path = os.path.join(os.environ['SystemRoot'], 'Fonts',
os.path.basename(src_path))
shutil.copy(src_path, dst_path)
# load the font in the current session
if not gdi32.AddFontResourceW(dst_path):
os.remove(dst_path)
raise WindowsError('AddFontResource failed to load "%s"' % src_path)
# notify running programs
user32.SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0,
SMTO_ABORTIFHUNG, 1000, None)
# store the fontname/filename in the registry
filename = os.path.basename(dst_path)
fontname = os.path.splitext(filename)[0]
# try to get the font's real name
cb = wintypes.DWORD()
if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), None,
GFRI_DESCRIPTION):
buf = (ctypes.c_wchar * cb.value)()
if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), buf,
GFRI_DESCRIPTION):
fontname = buf.value
is_truetype = wintypes.BOOL()
cb.value = ctypes.sizeof(is_truetype)
gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb),
ctypes.byref(is_truetype), GFRI_ISTRUETYPE)
if is_truetype:
fontname += ' (TrueType)'
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, FONTS_REG_PATH, 0,
winreg.KEY_SET_VALUE) as key:
winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename)
Essentially, use AddFontResourceW from gdi32 API of Windows to load a font and notify running programs by using SendMessage API - this will make the font visible in running programs.
To permanently install the font into Windows, you need to copy the font file into Fonts folder (C:\Windows\Fonts, or %userprofile%\AppData\Local\Microsoft\Windows\Fonts for per-user folder) and then add a key in registry at HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts (or HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts for per-user installation).

Python : No module webkit on windows 10

I am working on a Python application on Windows10 in which I want to use Webkit module from Python. I am getting an error as no module named webkit. I have installed pygtk and python, but I cannot find anything for webkit. Any ideas?
Code :
import os
import urlparse
import webkit
import gtk
view = webkit.WebView()
sw = gtk.ScrolledWindow()
sw.add(view)
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.add(sw)
win.resize(1080,1920)
win.show_all()
uri = 'resources/football.html'
uri = os.path.realpath(uri)
uri = urlparse.ParseResult('file', '', uri, '', '', '')
uri = urlparse.urlunparse(uri)
view.load_uri(uri)
gtk.main()
Thank you.
Firstly pygtk is a dead project and you shouldn't use it; PyGObject is the maintained bindings.
Secondly only a very old version of WebKitGtk supports Windows that is terribly insecure and unmaintained so you shouldn't use it.
So sadly WebKitGtk does not support Windows.

Python script just printing out blank page

I am using xampp and I am able to run simple python script on it so xampp is setup fine for python. I am trying to use pillow.
I have installed anaconda and did following in terminal
conda install pillow
If I run test.py below in terminal, it works fine. It prints format, size, mode.
But if I try it from web browser I'm getting blank page.
Here is test.py
#!/Library/Frameworks/anaconda/bin/python
print("Content-Type: text/html")
print()
print("<html><head><title>Python</title></head><body>")
from PIL import Image, ImageFilter
original = Image.open("Lenna.png")
print("<h5>The size of the Image is: </h5>")
print("<h2>size " + original.format, original.size, original.mode + "</h2>")
if I use cgitb.enable() I get following error
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/Applications/XAMPP/xamppfiles/cgi-bin/test7.py in ()
8 print("<html><head><title>Python</title></head><body>");
9 print("<h5>The size of the Image is: </h5>");
=> 10 from PIL import Image
11 original = Image.open("Lenna.png");
12 width, height = original.size;
PIL undefined, Image undefined
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/Image.py in ()
61 # Also note that Image.core is not a publicly documented interface,
62 # and should be considered private and subject to change.
=> 63 from PIL import _imaging as core
64 if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
65 raise ImportError("The _imaging extension was built for another "
PIL undefined, _imaging undefined, core = <PIL.Image._imaging_not_installed object>
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so, 2): Library not loaded: #loader_path/.dylibs/libtiff.5.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so Reason: Incompatible library version: _imaging.so requires version 8.0.0 or later, but libtiff.5.dylib provides version 6.0.0
args = ('dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0',)
msg = 'dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0'
name = '_imaging'
path = '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so'
with_traceback = <built-in method with_traceback of ImportError object>
Kind of an anti-answer, but unless you are doing it this way for academic reasons, you should try one of the more standard frameworks:
Flask
bottle.py
The two frameworks I listed above are examples of minimalist frameworks that do not get in your way. They take care of running your app and setting up routes. The minimum to use Flask is this:
from flask import Flask
from PIL import Image, ImageFilter
app = Flask(__name__)
#app.route("/")
def myview():
original = Image.open("Lenna.png")
return """
<html><head><title>Python</title></head>
<body>
<h5>The size of the Image is: </h5>
<h2>size {format}, {size}, {mode}</h2>
</body></html>""".format(
format=original.format,
size=original.size,
mode=original.mode)
app.run()
Next, if you want to make your app available, you only need to setup a reverse proxy in XAMPP (easy-peasy). I highly suggest using Flask; it comes with an awesome in-page debugger, courtesy of its sister project Werkzeug (lit. "toolbox").
Werkzeug debugger:

Python script for Blender failed

In Blender 2.62 I was using this script to display a point:
import bpy
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from add_utils import AddObjectHelper, add_object_data
data0=[]
data0.append((float(69.3456), float(36.4562), float(26.8232)))
me0 = bpy.data.meshes.new( name = "point cloud0")
me0.from_pydata( data0, [], [] )
me0.update()
add_object_data(bpy.context, me0, [])
After having updated to Blender 2.67a the execution returns a failure and the following error is reported in the console window:
ImportError: No module named 'add_utils'
Do you have any clue why this should not work anymore?
Thank you :)
Add the missing bpy_extras import at the start of the script
import bpy
import bpy_extras
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from bpy_extras import object_utils.object_data_add
from bpy_extras import AddObjectHelper
The API for add_object_data appears to have changed to object_data_add so you'll need to change that in the script too.
object_data_add(bpy.context, me0, [])

Categories

Resources