repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dot3k/backlight.py | library/dot3k/backlight.py | import colorsys
import math
from sys import exit
try:
from sn3218 import SN3218
except ImportError:
try:
import sn3218
except ImportError:
exit("This library requires the sn3218 module\nInstall with: sudo pip install sn3218")
else:
sn3218 = SN3218()
LED_R_R = 0x00
LED_R_G = 0x01
LED_R_B = 0x02
LED_M_R = 0x03
LED_M_G = 0x04
LED_M_B = 0x05
LED_L_R = 0x06
LED_L_G = 0x07
LED_L_B = 0x08
leds = [0x00] * 18
def use_rbg():
"""Swap the Green and Blue channels on the LED backlight
Use if you have a first batch Display-o-Tron 3K
"""
global LED_R_G, LED_R_B
global LED_M_G, LED_M_B
global LED_L_G, LED_L_B
(LED_R_G, LED_R_B) = (LED_R_B, LED_R_G)
(LED_M_G, LED_M_B) = (LED_M_B, LED_M_G)
(LED_L_G, LED_L_B) = (LED_L_B, LED_L_G)
def set_graph(value):
"""Light a number of bargraph LEDs depending upon value
:param hue: hue value between 0.0 and 1.0
"""
value *= 9
if value > 9:
value = 9
for i in range(9):
leds[9 + i] = 0
lit = int(math.floor(value))
for i in range(lit):
leds[9 + i] = 255
partial = lit
if partial < 9:
leds[9 + partial] = int((value % 1) * 255)
update()
def set(index, value):
"""Set a specific LED to a value
:param index (int): index of the LED from 0 to 18
:param value (int): brightness value from 0 to 255
"""
leds[index] = value
update()
def set_bar(index, value):
"""Set a value or values to one or more LEDs
:param index: starting index
:param value: a single int, or list of brightness values from 0 to 255
"""
if isinstance(value, int):
set(LED_R_R + 9 + (index % 9), value)
if isinstance(value, list):
for i, v in enumerate(value):
set(LED_R_R + 9 + ((index + i) % 9), v)
update()
def hue_to_rgb(hue):
"""Convert a hue to RGB brightness values
:param hue: hue value between 0.0 and 1.0
"""
rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
return [int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)]
def hue(hue):
"""Set the backlight LEDs to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
rgb(col_rgb[0], col_rgb[1], col_rgb[2])
def sweep(hue, range=0.08):
"""Set the backlight LEDs to a gradient centered on supplied hue
Supplying zero to range would be the same as hue()
:param hue: hue value between 0.0 and 1.0
:param range: range value to deviate the left and right hue
"""
left_hue((hue - range) % 1)
mid_hue(hue)
right_hue((hue + range) % 1)
def left_hue(hue):
"""Set the left backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
left_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def mid_hue(hue):
"""Set the middle backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
mid_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def right_hue(hue):
"""Set the right backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
right_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def left_rgb(r, g, b):
"""Set the left backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
set(LED_L_R, r)
set(LED_L_B, b)
set(LED_L_G, g)
update()
def mid_rgb(r, g, b):
"""Set the middle backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
set(LED_M_R, r)
set(LED_M_B, b)
set(LED_M_G, g)
update()
def right_rgb(r, g, b):
"""Set the right backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
set(LED_R_R, r)
set(LED_R_B, b)
set(LED_R_G, g)
update()
def rgb(r, g, b):
"""Set all backlights to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
left_rgb(r, g, b)
mid_rgb(r, g, b)
right_rgb(r, g, b)
def off():
"""Turn off the backlight."""
rgb(0, 0, 0)
def update():
"""Update backlight with changes to the LED buffer"""
sn3218.output(leds)
# set gamma correction for backlight to normalise brightness
g_channel_gamma = [int(value / 1.6) for value in sn3218.default_gamma_table]
sn3218.channel_gamma(1, g_channel_gamma)
sn3218.channel_gamma(4, g_channel_gamma)
sn3218.channel_gamma(7, g_channel_gamma)
r_channel_gamma = [int(value / 1.4) for value in sn3218.default_gamma_table]
sn3218.channel_gamma(0, r_channel_gamma)
sn3218.channel_gamma(3, r_channel_gamma)
sn3218.channel_gamma(6, r_channel_gamma)
w_channel_gamma = [int(value / 24) for value in sn3218.default_gamma_table]
for i in range(9, 18):
sn3218.channel_gamma(i, w_channel_gamma)
sn3218.enable()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dot3k/__init__.py | library/dot3k/__init__.py | __version__ = '2.0.3'
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dothat/lcd.py | library/dothat/lcd.py | from sys import exit
try:
import st7036
except ImportError:
exit("This library requires the st7036 module\nInstall with: sudo pip install st7036")
ROWS = 3
COLS = 16
lcd = st7036.st7036(register_select_pin=25, reset_pin=12)
lcd.clear()
def write(value):
"""Write a string to the current cursor position.
:param value: The string to write
"""
lcd.write(value)
def clear():
"""Clear the display and reset the cursor."""
lcd.clear()
def set_contrast(contrast):
"""Set the display contrast.
Raises TypeError if contrast is not an int
Raises ValueError if contrast is not in the range 0..0x3F
:param contrast: contrast value
"""
lcd.set_contrast(contrast)
def set_display_mode(enable=True, cursor=False, blink=False):
"""Set the cursor position in DRAM
:param offset: DRAM offset to place cursor
"""
lcd.set_display_mode(enable, cursor, blink)
def set_cursor_offset(offset):
"""Set the cursor position in DRAM
Calculates the cursor offset based on a row and column offset.
Raises ValueError if row and column are not within defined screen size
:param column: column to move the cursor to
:param row: row to move the cursor to
"""
lcd.set_cursor_offset(offset)
def set_cursor_position(column, row):
"""Sets the cursor position in DRAM based on a row and column offset.
Args:
column (int): column to move the cursor to
row (int): row to move the cursor to
Raises:
ValueError: if row and column are not within defined screen size
"""
lcd.set_cursor_position(column, row)
def create_animation(anim_pos, anim_map, frame_rate):
"""Create an animation in a given custom character slot
Each definition should be a list of 8 bytes describing the custom character for that frame,
:param anim_pos: Character slot from 0 to 7 to store animation
:param anim_map: A list of custom character definitions
:param frame_rate: Speed of animation in frames-per-second
"""
lcd.create_animation(anim_pos, anim_map, frame_rate)
def update_animations():
"""Update animations onto the LCD
Uses wall time to figure out which frame is current for
each animation, and then updates the animations character
slot to the contents of that frame.
Only one frame, the current one, is ever stored on the LCD.
"""
lcd.update_animations()
def create_char(char_pos, char_map):
"""Create a character in the LCD memory
The st7036 has 8 slots for custom characters.
A char is defined as a list of 8 integers with the
upper 5 bits setting the state of each row of pixels.
Note: These slots are also used for animations!
:param char_pos: Char slot to use (0-7)
:param char_map: List of 8 integers containing bitmap
"""
lcd.create_char(char_pos, char_map)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dothat/touch.py | library/dothat/touch.py | from sys import exit
try:
from cap1xxx import Cap1166, PID_CAP1166
except ImportError:
exit("This library requires the cap1xxx module\nInstall with: sudo pip install cap1xxx")
I2C_ADDR = 0x2c
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 5
BUTTON = 4
CANCEL = 0
_cap1166 = Cap1166(i2c_addr=I2C_ADDR)
_cap1166._write_byte(0x26, 0b00111111) # Force recalibration
for x in range(6):
_cap1166.set_led_linking(x, False)
def high_sensitivity():
"""Switch to high sensitivity mode
This predetermined high sensitivity mode is for using
touch through 3mm perspex or similar materials.
"""
_cap1166._write_byte(0x00, 0b11000000)
_cap1166._write_byte(0x1f, 0b00000000)
def enable_repeat(enable):
"""Enable touch hold repeat
If enable is true, repeat will be enabled. This will
trigger new touch events at the set repeat_rate when
a touch input is held.
:param enable: enable/disable repeat: True/False
"""
if enable:
_cap1166.enable_repeat(0b11111111)
else:
_cap1166.enable_repeat(0b00000000)
def set_repeat_rate(rate):
"""Set hold repeat rate
Repeat rate values are clamped to the nearest 35ms,
values from 35 to 560 are valid.
:param rate: time in ms from 35 to 560
"""
_cap1166.set_repeat_rate(rate)
def on(buttons, bounce=-1):
"""Handle a press of one or more buttons
Decorator. Use with @captouch.on(UP)
:param buttons: List, or single instance of cap touch button constant
:param bounce: Maintained for compatibility with Dot3k joystick, unused
"""
buttons = buttons if isinstance(buttons, list) else [buttons]
def register(handler):
for button in buttons:
_cap1166.on(channel=button, event='press', handler=handler)
_cap1166.on(channel=button, event='held', handler=handler)
return register
def bind_defaults(menu):
"""Bind the default controls to a menu instance
This should be used in conjunction with a menu class instance
to bind touch inputs to the default controls.
"""
@on(UP)
def handle_up(ch, evt):
menu.up()
@on(DOWN)
def handle_down(ch, evt):
menu.down()
@on(LEFT)
def handle_left(ch, evt):
menu.left()
@on(RIGHT)
def handle_right(ch, evt):
menu.right()
@on(BUTTON)
def handle_button(ch, evt):
menu.select()
@on(CANCEL)
def handle_cancel(ch, evt):
menu.cancel()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dothat/backlight.py | library/dothat/backlight.py | import colorsys
from sys import exit
try:
from sn3218 import SN3218
except ImportError:
try:
import sn3218
except ImportError:
exit("This library requires the sn3218 module\nInstall with: sudo pip install sn3218")
else:
sn3218 = SN3218()
try:
import cap1xxx
except ImportError:
exit("This library requires the cap1xxx module\nInstall with: sudo pip install cap1xxx")
cap = cap1xxx.Cap1166(i2c_addr=0x2C, skip_init=True)
NUM_LEDS = 6
STEP_VALUE = 16
leds = [0x00] * 18 # B G R, B G R, B G R, B G R, B G R, B G R
# set gamma correction for backlight to normalise brightness
g_channel_gamma = [int(value / 1.6) for value in sn3218.default_gamma_table]
r_channel_gamma = [int(value / 1.4) for value in sn3218.default_gamma_table]
for x in range(0, 18, 3):
sn3218.channel_gamma(x + 1, g_channel_gamma)
sn3218.channel_gamma(x + 2, r_channel_gamma)
sn3218.enable()
graph_set_led_state = cap.set_led_state
graph_set_led_polarity = cap.set_led_polarity
graph_set_led_duty = cap.set_led_direct_duty
def use_rbg():
"""Does nothing.
Implemented for library compatibility with Dot3k backlight.
"""
pass
def graph_off():
cap._write_byte(cap1xxx.R_LED_POLARITY, 0b00000000)
cap._write_byte(cap1xxx.R_LED_OUTPUT_CON, 0b00000000)
def set_graph(percentage):
"""Light a number of bargraph LEDs depending upon value
:param hue: hue value between 0.0 and 1.0
"""
cap._write_byte(cap1xxx.R_LED_DIRECT_RAMP, 0b00000000)
cap._write_byte(cap1xxx.R_LED_BEHAVIOUR_1, 0b00000000)
cap._write_byte(cap1xxx.R_LED_BEHAVIOUR_2, 0b00000000)
# The Cap 1xxx chips do *not* have full per-LED PWM
# brightness control. However...
# They have the ability to define what on/off actually
# means, plus invert the state of any LED.
total_value = STEP_VALUE * NUM_LEDS
actual_value = int(total_value * percentage)
set_polarity = 0b00000000
set_state = 0b00000000
set_duty = 0 # Value from 0 to 15
for x in range(NUM_LEDS):
if actual_value >= STEP_VALUE:
set_polarity |= 1 << (NUM_LEDS - 1 - x)
if 0 < actual_value < STEP_VALUE:
set_state |= 1 << (NUM_LEDS - 1 - x)
set_duty = actual_value << 4
actual_value -= STEP_VALUE
cap._write_byte(cap1xxx.R_LED_DIRECT_DUT, set_duty)
cap._write_byte(cap1xxx.R_LED_POLARITY, set_polarity)
cap._write_byte(cap1xxx.R_LED_OUTPUT_CON, set_state)
def set(index, value):
"""Set a specific backlight LED to a value
:param index (int): index of the LED from 0 to 17
:param value (int): brightness value from 0 to 255
"""
index = index if isinstance(index, list) else [index]
for i in index:
leds[i] = value
update()
def set_bar(index, value):
"""Does nothing.
Implemented for library compatibility with Dot3k backlight.
"""
pass
def hue_to_rgb(hue):
"""Convert a hue to RGB brightness values
:param hue: hue value between 0.0 and 1.0
"""
rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
return [int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)]
def hue(hue):
"""Set the backlight LEDs to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
rgb(col_rgb[0], col_rgb[1], col_rgb[2])
def sweep(hue, sweep_range=0.0833):
"""Set the backlight LEDs to a gradient centered on supplied hue
Supplying zero to range would be the same as hue()
:param hue: hue value between 0.0 and 1.0
:param range: range value to deviate the left and right hue
"""
global leds
for x in range(0, 18, 3):
rgb = hue_to_rgb((hue + (sweep_range * (x / 3))) % 1)
rgb.reverse()
leds[x:x + 3] = rgb
update()
def left_hue(hue):
"""Set the left backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
left_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def mid_hue(hue):
"""Set the middle backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
mid_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def right_hue(hue):
"""Set the right backlight to supplied hue
:param hue: hue value between 0.0 and 1.0
"""
col_rgb = hue_to_rgb(hue)
right_rgb(col_rgb[0], col_rgb[1], col_rgb[2])
update()
def left_rgb(r, g, b):
"""Set the left backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
single_rgb(0, r, g, b, False)
single_rgb(1, r, g, b, False)
update()
def mid_rgb(r, g, b):
"""Set the middle backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
single_rgb(2, r, g, b, False)
single_rgb(3, r, g, b, False)
update()
def right_rgb(r, g, b):
"""Set the right backlight to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
single_rgb(4, r, g, b, False)
single_rgb(5, r, g, b, False)
update()
def single_rgb(led, r, g, b, auto_update=True):
"""A single backlight LED to the supplied r, g, b colour
The `auto_update` parameter will trigger a write to the LEDs
after the r, g, b colour has been set. Omit it and manually
call `update()` to batch multiple LED changes into one update.
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
:param auto_update: autmatically update the LEDs
"""
global leds
leds[(led * 3)] = b
leds[(led * 3) + 1] = g
leds[(led * 3) + 2] = r
if auto_update:
update()
def rgb(r, g, b):
"""Set all backlights to supplied r, g, b colour
:param r: red value between 0 and 255
:param g: green value between 0 and 255
:param b: blue value between 0 and 255
"""
global leds
leds = [b, g, r] * 6
update()
def off():
"""Turn off the backlight."""
rgb(0, 0, 0)
def update():
"""Update backlight with changes to the LED buffer"""
sn3218.output(leds)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/library/dothat/__init__.py | library/dothat/__init__.py | __version__ = '2.0.3'
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/automenu.py | examples/dot3k/advanced/automenu.py | #!/usr/bin/env python
import sys
import time
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
from dot3k.menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import IPAddress, GraphTemp, GraphCPU, GraphNetSpeed
from plugins.wlan import Wlan
print("""
This example uses automation to advance through each menu item.
You should see each menu item appear in turn. However use-input will not be accepted.
Press CTRL+C to exit.
""")
menu = Menu({
'Clock': Clock(),
'IP': IPAddress(),
'CPU': GraphCPU(),
'Temp': GraphTemp()
},
lcd,
None,
30)
def millis():
return int(round(time.time() * 1000.0))
def advance():
global last
if millis() > last + (delay * 1000.0):
menu.cancel()
menu.down()
menu.right()
last = millis()
last = millis()
delay = 2 # In seconds
while 1:
advance()
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/orderedmenu.py | examples/dot3k/advanced/orderedmenu.py | #!/usr/bin/env python
import sys
import time
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
from dot3k.menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import IPAddress, GraphTemp, GraphCPU, GraphNetSpeed
from plugins.utils import Backlight, Contrast
print("""
This advanced example uses the menu framework.
It gives you an example of a menu created with a specific order.
Press CTRL+C to exit.
""")
class SpaceInvader(MenuOption):
"""
A silly example "plug-in" showing an
animated space invader.
"""
def __init__(self):
self.start = self.millis()
self.invader = [
[14, 31, 21, 31, 9, 18, 9, 18],
[14, 31, 21, 31, 18, 9, 18, 9]
]
MenuOption.__init__(self)
def redraw(self, menu):
now = self.millis()
x = int((self.start - now) / 200 % 16)
menu.lcd.create_char(0, self.invader[int((self.start - now) / 400 % 2)])
menu.write_row(0, 'Space Invader!')
menu.write_row(1, (' ' * x) + chr(0))
menu.clear_row(2)
my_invader = SpaceInvader()
menu = Menu(
None,
lcd,
my_invader,
5)
"""
If you want menu items to appear in a defined order, you must
add them one at a time using 'add_item'. This method accepts
a plugin instance, plus the path where you want it to appear.
Instances of classes derived from MenuOption can
be used as menu items to show information or change settings.
See GraphTemp, GraphCPU, Contrast and Backlight for examples.
"""
menu.add_item('Space Invader', my_invader)
menu.add_item('Clock', Clock())
menu.add_item('Status/IP', IPAddress())
menu.add_item('Status/Test', '')
menu.add_item('Status/CPU', GraphCPU())
menu.add_item('Status/Arrr', 'Blah blah')
menu.add_item('Status/Temp', GraphTemp())
menu.add_item('Settings/Display/Contrast', Contrast(lcd)),
menu.add_item('Settings/Display/Backlight', Backlight(backlight))
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.joystick
"""
REPEAT_DELAY = 0.5
@nav.on(nav.UP)
def handle_up(pin):
menu.up()
nav.repeat(nav.UP, menu.up, REPEAT_DELAY, 0.9)
@nav.on(nav.DOWN)
def handle_down(pin):
menu.down()
nav.repeat(nav.DOWN, menu.down, REPEAT_DELAY, 0.9)
@nav.on(nav.LEFT)
def handle_left(pin):
menu.left()
nav.repeat(nav.LEFT, menu.left, REPEAT_DELAY, 0.9)
@nav.on(nav.RIGHT)
def handle_right(pin):
menu.right()
nav.repeat(nav.RIGHT, menu.right, REPEAT_DELAY, 0.9)
@nav.on(nav.BUTTON)
def handle_button(pin):
menu.select()
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/control.py | examples/dot3k/advanced/control.py | #!/usr/bin/env python
import sys
import time
import dot3k.lcd as lcd
import dot3k.backlight as backlight
import dot3k.joystick as nav
from menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.deluge import Deluge
from plugins.text import Text
from plugins import Volume, Backlight, Contrast, GraphTemp, GraphCPU, Clock, Radio, Stocks
import utils.usbkeyboard as keyboard
print("""
This example builds upon the others and incorporates idle plugins,
remote control support, and more.
To use this example you need a Rii mini wireless keyboard plugged into USB!
Press CTRL+C to exit.
""")
my_clock = Clock()
menu = Menu(structure={
'Deluge': Deluge(),
'Clock': my_clock,
'Stocks': Stocks(),
'Radio': Radio(),
'Status': {
'CPU': GraphCPU(),
'Temp': GraphTemp()
},
'Settings': {
'Volume': Volume(),
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
},
lcd=lcd,
idle_handler=my_clock,
idle_time=3,
input_handler=Text())
"""
usbkeyboard provides the same methods as joystick
so it's a drop-in replacement!
"""
@keyboard.on(keyboard.UP)
def handle_up(pin):
menu.up()
@keyboard.on(keyboard.DOWN)
def handle_down(pin):
menu.down()
@keyboard.on(keyboard.LEFT)
def handle_left(pin):
menu.left()
@keyboard.on(keyboard.RIGHT)
def handle_right(pin):
menu.right()
@keyboard.on(keyboard.BUTTON)
def handle_button(pin):
menu.button()
REPEAT_DELAY = 0.5
REPEAT_DATE = 0.99
@nav.on(nav.UP)
def handle_up(pin):
menu.up()
nav.repeat(nav.UP, menu.up, REPEAT_DELAY, 0.99)
@nav.on(nav.DOWN)
def handle_down(pin):
menu.down()
nav.repeat(nav.DOWN, menu.down, REPEAT_DELAY, 0.99)
@nav.on(nav.LEFT)
def handle_left(pin):
menu.left()
nav.repeat(nav.LEFT, menu.left, REPEAT_DELAY, 0.99)
@nav.on(nav.RIGHT)
def handle_right(pin):
menu.right()
nav.repeat(nav.RIGHT, menu.right, REPEAT_DELAY, 0.99)
@nav.on(nav.BUTTON)
def handle_button(pin):
menu.select()
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/menu.py | examples/dot3k/advanced/menu.py | #!/usr/bin/env python
import sys
import time
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
from dot3k.menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import IPAddress, GraphTemp, GraphCPU, GraphNetSpeed
from plugins.utils import Backlight, Contrast
from plugins.volume import Volume
print("""
This advanced example uses the menu framework.
It gives you a basic menu setup with plugins. You should be able to view system info and adjust settings!
Press CTRL+C to exit.
""")
class SpaceInvader(MenuOption):
"""
A silly example "plug-in" showing an
animated space invader.
"""
def __init__(self):
self.start = self.millis()
self.invader = [
[14, 31, 21, 31, 9, 18, 9, 18],
[14, 31, 21, 31, 18, 9, 18, 9]
]
MenuOption.__init__(self)
def redraw(self, menu):
now = self.millis()
x = int((self.start - now) / 200 % 16)
menu.lcd.create_char(0, self.invader[int((self.start - now) / 400 % 2)])
menu.write_row(0, 'Space Invader!')
menu.write_row(1, (' ' * x) + chr(0))
menu.clear_row(2)
"""
Using a set of nested lists you can describe
the menu you want to display on dot3k.
Instances of classes derived from MenuOption can
be used as menu items to show information or change settings.
See GraphTemp, GraphCPU, Contrast and Backlight for examples.
"""
my_invader = SpaceInvader()
menu = Menu({
'Space Invader': my_invader,
'Clock': Clock(),
'Status': {
'IP': IPAddress(),
'CPU': GraphCPU(),
'Temp': GraphTemp()
},
'Settings': {
'Volume': Volume(),
'Display': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
}
},
lcd,
my_invader,
30)
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.joystick
"""
REPEAT_DELAY = 0.5
@nav.on(nav.UP)
def handle_up(pin):
menu.up()
nav.repeat(nav.UP, menu.up, REPEAT_DELAY, 0.9)
@nav.on(nav.DOWN)
def handle_down(pin):
menu.down()
nav.repeat(nav.DOWN, menu.down, REPEAT_DELAY, 0.9)
@nav.on(nav.LEFT)
def handle_left(pin):
menu.left()
nav.repeat(nav.LEFT, menu.left, REPEAT_DELAY, 0.9)
@nav.on(nav.RIGHT)
def handle_right(pin):
menu.right()
nav.repeat(nav.RIGHT, menu.right, REPEAT_DELAY, 0.9)
@nav.on(nav.BUTTON)
def handle_button(pin):
menu.select()
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/animations.py | examples/dot3k/advanced/animations.py | #!/usr/bin/env python
import copy
import datetime
import math
import time
from sys import exit
try:
import psutil
except ImportError:
exit("This library requires the psutil module\nInstall with: sudo pip install psutil")
import dot3k.backlight as backlight
import dot3k.lcd as lcd
print("""
This example shows you how to create animations on Display-o-Tron!
You should see a collection of animated icons on your display.
Press CTRL+C to exit.
""")
lcd.write(chr(0) + 'Ooo! Such time' + chr(0))
lcd.set_cursor_position(0, 2)
lcd.write(chr(1) + chr(4) + ' Very Wow! ' + chr(3) + chr(2) + chr(5))
pirate = [
[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x16, 0x06, 0x00, 0x08, 0x03, 0x1e],
[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x05, 0x01, 0x00, 0x02, 0x08, 0x07]
]
heart = [
[0x00, 0x0a, 0x1f, 0x1f, 0x1f, 0x0e, 0x04, 0x00],
[0x00, 0x00, 0x0a, 0x0e, 0x0e, 0x04, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x0e, 0x04, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x0a, 0x0e, 0x0e, 0x04, 0x00, 0x00]
]
raa = [
[0x1f, 0x1d, 0x19, 0x13, 0x17, 0x1d, 0x19, 0x1f],
[0x1f, 0x17, 0x1d, 0x19, 0x13, 0x17, 0x1d, 0x1f],
[0x1f, 0x13, 0x17, 0x1d, 0x19, 0x13, 0x17, 0x1f],
[0x1f, 0x19, 0x13, 0x17, 0x1d, 0x19, 0x13, 0x1f]
]
arr = [
[31, 14, 4, 0, 0, 0, 0, 0],
[0, 31, 14, 4, 0, 0, 0, 0],
[0, 0, 31, 14, 4, 0, 0, 0],
[0, 0, 0, 31, 14, 4, 0, 0],
[0, 0, 0, 0, 31, 14, 4, 0],
[0, 0, 0, 0, 0, 31, 14, 4],
[4, 0, 0, 0, 0, 0, 31, 14],
[14, 4, 0, 0, 0, 0, 0, 31]
]
char = [
[12, 11, 9, 9, 25, 25, 3, 3],
[0, 15, 9, 9, 9, 25, 27, 3],
[3, 13, 9, 9, 9, 27, 27, 0],
[0, 15, 9, 9, 9, 25, 27, 3]
]
pacman = [
[0x0e, 0x1f, 0x1d, 0x1f, 0x18, 0x1f, 0x1f, 0x0e],
[0x0e, 0x1d, 0x1e, 0x1c, 0x18, 0x1c, 0x1e, 0x0f]
]
def getAnimFrame(char, fps):
return char[int(round(time.time() * fps) % len(char))]
cpu_sample_count = 200
cpu_samples = [0] * cpu_sample_count
hue = 0.0
while True:
hue += 0.008
backlight.sweep(hue)
cpu_samples.append(psutil.cpu_percent() / 100.0)
cpu_samples.pop(0)
cpu_avg = sum(cpu_samples) / cpu_sample_count
backlight.set_graph(cpu_avg)
if hue > 1.0:
hue = 0.0
lcd.create_char(0, getAnimFrame(char, 4))
lcd.create_char(1, getAnimFrame(arr, 16))
lcd.create_char(2, getAnimFrame(raa, 8))
lcd.create_char(3, getAnimFrame(pirate, 2))
lcd.create_char(4, getAnimFrame(heart, 4))
lcd.create_char(5, getAnimFrame(pacman, 3))
lcd.set_cursor_position(0, 1)
t = datetime.datetime.now().strftime("%H:%M:%S.%f")
lcd.write(t)
time.sleep(0.005)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/backlight.py | examples/dot3k/advanced/backlight.py | #!/usr/bin/env python
import time
import dot3k.backlight as backlight
import dot3k.lcd as lcd
print("""
This example shows a range of different backlight techniques for Display-o-Tron.
You should see the backlight go Red, Green, Blue, White and then Rainbow!
Press CTRL+C to exit.
""")
pirate = [
[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x16, 0x06, 0x00, 0x08, 0x03, 0x1e],
[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x05, 0x01, 0x00, 0x02, 0x08, 0x07]
]
def get_anim_frame(anim, fps):
return anim[int(round(time.time() * fps) % len(anim))]
lcd.set_cursor_position(1, 0)
lcd.write('Display-o-tron')
lcd.write(' ' + chr(0) + '3000 ')
lcd.create_char(0, get_anim_frame(pirate, 4))
while 1:
backlight.rgb(255, 0, 0)
time.sleep(1)
backlight.rgb(0, 255, 0)
time.sleep(1)
backlight.rgb(0, 0, 255)
time.sleep(1)
backlight.rgb(255, 255, 255)
time.sleep(1)
for i in range(0, 360):
backlight.hue(i / 360.0)
time.sleep(0.01)
for i in range(0, 360):
backlight.sweep(i / 360.0)
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/radio.py | examples/dot3k/advanced/radio.py | #!/usr/bin/env python
import sys
import time
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
from dot3k.menu import Menu
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import GraphCPU, GraphTemp
from plugins.radio import Radio
from plugins.utils import Backlight, Contrast
from plugins.volume import Volume
print("""
This advanced example uses the menu framework.
Providing you have VLC and extra dependencies installed, it should function as an internet radio!
Press CTRL+C to exit.
""")
# We want to use clock both as an option
# and as the idle plugin
clock = Clock(backlight)
"""
Using a set of nested dictionaries you can describe
the menu you want to display on dot3k.
A nested dictionary describes a submenu.
An instance of a plugin class ( derived from MenuOption ) can be used for things like settings, radio, etc
A function name will call that function.
"""
menu = Menu({
'Clock': clock,
'Radio Stream': Radio(),
'Volume': Volume(backlight),
'Status': {
'CPU': GraphCPU(backlight),
'Temp': GraphTemp()
},
'Settings': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
},
lcd, # Draw to dot3k.lcd
clock, # Idle with the clock plugin,
10 # Idle after 10 seconds
)
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.joystick
Repeat delay determines how quickly holding the joystick
in a direction will start to trigger repeats
"""
REPEAT_DELAY = 0.5
@nav.on(nav.UP)
def handle_up(pin):
menu.up()
nav.repeat(nav.UP, menu.up, REPEAT_DELAY, 0.9)
@nav.on(nav.DOWN)
def handle_down(pin):
menu.down()
nav.repeat(nav.DOWN, menu.down, REPEAT_DELAY, 0.9)
@nav.on(nav.LEFT)
def handle_left(pin):
menu.left()
nav.repeat(nav.LEFT, menu.left, REPEAT_DELAY, 0.9)
@nav.on(nav.RIGHT)
def handle_right(pin):
menu.right()
nav.repeat(nav.RIGHT, menu.right, REPEAT_DELAY, 0.9)
@nav.on(nav.BUTTON)
def handle_button(pin):
menu.select()
while 1:
# Redraw the menu, since we don't want to hand this off to a thread
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/advanced/game.py | examples/dot3k/advanced/game.py | #!/usr/bin/env python
import sys
import time
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
from dot3k.menu import Menu
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.debris import Debris
from plugins.utils import Backlight, Contrast
print("""
This advanced example uses the menu framework.
It loads the debris game plugin. Your score is time survived in seconds, see how well you can do!
Press CTRL+C to exit.
""")
menu = Menu({
'Debris Game': Debris(),
'Settings': {
'Display': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
}
},
lcd)
REPEAT_DELAY = 0.5
@nav.on(nav.UP)
def handle_up(pin):
menu.up()
nav.repeat(nav.UP, menu.up, REPEAT_DELAY, 0.9)
@nav.on(nav.DOWN)
def handle_down(pin):
menu.down()
nav.repeat(nav.DOWN, menu.down, REPEAT_DELAY, 0.9)
@nav.on(nav.LEFT)
def handle_left(pin):
menu.left()
nav.repeat(nav.LEFT, menu.left, REPEAT_DELAY, 0.9)
@nav.on(nav.RIGHT)
def handle_right(pin):
menu.right()
nav.repeat(nav.RIGHT, menu.right, REPEAT_DELAY, 0.9)
@nav.on(nav.BUTTON)
def handle_button(pin):
menu.select()
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/ipaddr.py | examples/dot3k/basic/ipaddr.py | #!/usr/bin/env python
import fcntl
import socket
import struct
import dot3k.lcd as lcd
def get_addr(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15].encode('utf-8'))
)[20:24])
except IOError:
return 'Not Found!'
wlan0 = get_addr('wlan0')
eth0 = get_addr('eth0')
host = socket.gethostname()
lcd.clear()
lcd.set_cursor_position(0,0)
lcd.write('{}'.format(host))
lcd.set_cursor_position(0,1)
if eth0 != 'Not Found!':
lcd.write(eth0)
else:
lcd.write('eth0 {}'.format(eth0))
lcd.set_cursor_position(0,2)
if wlan0 != 'Not Found!':
lcd.write(wlan0)
else:
lcd.write('wlan0 {}'.format(wlan0))
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/mouse.py | examples/dot3k/basic/mouse.py | #!/usr/bin/env python
import signal
from sys import exit
try:
import uinput
except ImportError:
exit("This script requires the uinput module\nInstall with: sudo pip install uinput")
import dot3k.joystick as nav
print("""
This example shows you how to use the Display-o-Tron 3000 Joystick as a mouse.
You'll need to be running a desktop environment to use this.
If you move the joystick, your mouse cursor should move.
Press CTRL+C to exit.
""")
"""
The joystick provides the @joystick.on() decorator
to make it super easy to attach handlers to each button.
"""
device = uinput.Device([
uinput.BTN_LEFT,
uinput.REL_X,
uinput.REL_Y
])
delay = 0.1
ramp = 0.5
@nav.on(nav.UP)
def handle_up(pin):
device.emit(uinput.REL_Y, -1)
nav.repeat(nav.UP, lambda: device.emit(uinput.REL_Y, -1), delay, ramp)
@nav.on(nav.DOWN)
def handle_down(pin):
device.emit(uinput.REL_Y, 1)
nav.repeat(nav.DOWN, lambda: device.emit(uinput.REL_Y, 1), delay, ramp)
@nav.on(nav.LEFT)
def handle_left(pin):
device.emit(uinput.REL_X, -1)
nav.repeat(nav.LEFT, lambda: device.emit(uinput.REL_X, -1), delay, ramp)
@nav.on(nav.RIGHT)
def handle_right(pin):
device.emit(uinput.REL_X, 1)
nav.repeat(nav.RIGHT, lambda: device.emit(uinput.REL_X, 1), delay, ramp)
@nav.on(nav.BUTTON, 100)
def handle_button(pin):
device.emit_click(uinput.BTN_LEFT)
# Prevent the script exiting!
signal.pause()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/joystick.py | examples/dot3k/basic/joystick.py | #!/usr/bin/env python
import signal
import dot3k.backlight as backlight
import dot3k.joystick as nav
import dot3k.lcd as lcd
print("""
This example shows you how to use the Display-o-Tron 3000 Joystick.
If you press a joystick direction, you should see the LCD change accordingly.
Press CTRL+C to exit.
""")
"""
The joystick provides the @joystick.on() decorator
to make it super easy to attach handlers to each button.
"""
@nav.on(nav.UP)
def handle_up(pin):
print("Up pressed!")
lcd.clear()
backlight.rgb(255, 0, 0)
lcd.write("Up up and away!")
@nav.on(nav.DOWN)
def handle_down(pin):
print("Down pressed!")
lcd.clear()
backlight.rgb(0, 255, 0)
lcd.write("Down down doobie down!")
@nav.on(nav.LEFT)
def handle_left(pin):
print("Left pressed!")
lcd.clear()
backlight.rgb(0, 0, 255)
lcd.write("Leftie left left!")
@nav.on(nav.RIGHT)
def handle_right(pin):
print("Right pressed!")
lcd.clear()
backlight.rgb(0, 255, 255)
lcd.write("Rightie tighty!")
@nav.on(nav.BUTTON)
def handle_button(pin):
print("Button pressed!")
lcd.clear()
backlight.rgb(255, 255, 255)
lcd.write("Ouch!")
# Prevent the script exiting!
signal.pause()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/hue.py | examples/dot3k/basic/hue.py | #!/usr/bin/env python
import colorsys
import dot3k.backlight as backlight
print("""
This example shows how to set the backlight to a hue!
It uses colorsys, rather than the built-in hue function, to show you a colour conversion in Python.
Press CTRL+C to exit.
""")
hue = 0
while True:
r, g, b = [int(x * 255.0) for x in colorsys.hsv_to_rgb(hue / 360.0, 1.0, 1.0)]
backlight.rgb(r, b, g)
hue += 1
hue %= 360
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/hello_world.py | examples/dot3k/basic/hello_world.py | #!/usr/bin/env python
import dot3k.lcd as lcd
print("""
This example shows a basic "Hello World" on the LCD.
You should see "Hello World" displayed on your LCD!
Press CTRL+C to exit.
""")
# Clear the LCD and display Hello World
lcd.clear()
lcd.write("Hello World")
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/backlight.py | examples/dot3k/basic/backlight.py | #!/usr/bin/env python
import time
import dot3k.backlight as backlight
import dot3k.lcd as lcd
print("""
This example shows you a feature of the Dot HAT backlight.
You should see the backlight go white, then multi-coloured.
Press CTRL+C to exit.
""")
# Clear the LCD and display Hello World
lcd.clear()
lcd.write("Hello World")
# Set all the backlights to white
backlight.rgb(255, 255, 255)
time.sleep(1)
# Set the backlights independently
backlight.left_rgb(255, 0, 0)
backlight.mid_rgb(255, 0, 255)
backlight.right_rgb(0, 0, 255)
time.sleep(1)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/clock.py | examples/dot3k/basic/clock.py | #!/usr/bin/env python
segone = [
0b11111,
0b11111,
0b11111,
0x0,
0x0,
0x0,
0x0,
0x0,
]
segtwo = [
0b11111,
0b11111,
0b11111,
0b00111,
0b00111,
0b00111,
0b00111,
0b00111,
]
segthree = [
0b11111,
0b11111,
0b11111,
0b11100,
0b11100,
0b11100,
0b11100,
0b11100,
]
segfour = [
0b11100,
0b11100,
0b11100,
0b11100,
0b11100,
0b11100,
0b11100,
0b11100,
]
segfive = [
0b00111,
0b00111,
0b00111,
0b00111,
0b00111,
0b00111,
0b00111,
0b00111,
]
segsix = [
0b00111,
0b00111,
0b00111,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000,
]
segdot = [
0b00000,
0b00000,
0b01110,
0b01110,
0b01110,
0b00000,
0b00000,
0b00000,
]
number = {
0: [3, 2, 4, 5, 1, 1],
1: [0, 5, 0, 5, 0, 6],
2: [1, 2, 3, 1, 1, 1],
3: [1, 2, 1, 2, 1, 1],
4: [4, 5, 1, 2, 0, 6],
5: [3, 1, 1, 2, 1, 1],
6: [3, 1, 3, 2, 1, 1],
7: [1, 2, 0, 5, 0, 6],
8: [3, 2, 3, 2, 1, 1],
9: [3, 2, 1, 2, 1, 1],
'dot': [7, 7, 0],
'empty': [0, 0, 0],
}
# setup character
from dot3k import lcd, backlight
from datetime import datetime
import time
backlight.rgb(61, 255, 129)
lcd.set_contrast(45)
lcd.set_display_mode(True, False, False)
lcd.create_char(0, [0, 0, 0, 0, 0, 0, 0, 0])
lcd.create_char(1, segone)
lcd.create_char(2, segtwo)
lcd.create_char(3, segthree)
lcd.create_char(4, segfour)
lcd.create_char(5, segfive)
lcd.create_char(6, segsix)
lcd.create_char(7, segdot)
lcd.clear()
running = True
tick = False
while running:
now = datetime.now()
second = 'dot' if tick else 'empty'
tick = not tick
chars = [now.hour / 10, now.hour % 10, second, now.minute / 10, now.minute % 10]
pos = 0
for char in chars:
char = number[char]
width = len(char) / 3
for index, num in enumerate(char):
lcd.set_cursor_position(index % width + pos, index / width)
lcd.write(chr(num))
pos += width + 1
time.sleep(0.5)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dot3k/basic/bargraph.py | examples/dot3k/basic/bargraph.py | #!/usr/bin/env python
import time
import dot3k.backlight as backlight
import dot3k.lcd as lcd
print("""
This example shows you different ways of setting the bargraph.
You should see the graph light up in sequence and then fade in.
Press CTRL+C to exit.
""")
# Clear the LCD and display Hello World
lcd.clear()
lcd.write("Hello World")
# Turn off the backlight
backlight.rgb(0, 0, 0)
"""
set_graph accepts a float between 0.0 and 1.0
and lights up the LEDs accordingly
"""
for i in range(100):
backlight.set_graph(i / 100.0)
time.sleep(0.05)
"""
set_bar will set a specific bargraph LED to
a brightness between 0 and 255
"""
for i in range(256):
backlight.set_bar(0, [255 - i] * 9)
time.sleep(0.01)
backlight.set_graph(0)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/advanced/backlight-timeout.py | examples/dothat/advanced/backlight-timeout.py | #!/usr/bin/env python
import sys
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
import dothat.touch as nav
from dot3k.menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import IPAddress, GraphTemp, GraphCPU, GraphNetSpeed
from plugins.text import Text
from plugins.utils import Backlight, Contrast
from plugins.wlan import Wlan
print("""
This advanced example uses the menu framework.
It gives you a basic menu setup with plugins. You should be able
to view system info and adjust settings!
Press CTRL+C to exit.
""")
class BacklightIdleTimeout(MenuOption):
def __init__(self, backlight):
self.backlight = backlight
self.r = 255
self.g = 255
self.b = 255
MenuOption.__init__(self)
def setup(self, config):
self.config = config
self.r = int(self.get_option('Backlight', 'r', 255))
self.g = int(self.get_option('Backlight', 'g', 255))
self.b = int(self.get_option('Backlight', 'b', 255))
def cleanup(self):
print("Idle timeout expired. Turning on backlight!")
self.backlight.rgb(self.r, self.g, self.b)
def begin(self):
print("Idle timeout triggered. Turning off backlight!")
self.backlight.rgb(0, 0, 0)
"""
Using a set of nested lists you can describe
the menu you want to display on dot3k.
Instances of classes derived from MenuOption can
be used as menu items to show information or change settings.
See GraphTemp, GraphCPU, Contrast and Backlight for examples.
"""
backlight_idle = BacklightIdleTimeout(backlight)
menu = Menu(
structure={
'WiFi': Wlan(),
'Clock': Clock(backlight),
'Status': {
'IP': IPAddress(),
'CPU': GraphCPU(backlight),
'Temp': GraphTemp()
},
'Settings': {
'Display': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
}
},
lcd=lcd,
idle_handler=backlight_idle,
idle_time=5,
input_handler=Text())
# Pass the configuration into the idle handler,
# since the menu class does not do this!
backlight_idle.setup(menu.config)
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.touch
"""
nav.bind_defaults(menu)
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/advanced/menu.py | examples/dothat/advanced/menu.py | #!/usr/bin/env python
import sys
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
import dothat.touch as nav
from dot3k.menu import Menu, MenuOption
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import IPAddress, GraphTemp, GraphCPU, GraphNetSpeed
from plugins.text import Text
from plugins.utils import Backlight, Contrast
from plugins.wlan import Wlan
print("""
This advanced example uses the menu framework.
It gives you a basic menu setup with plugins. You should be able to view system info and adjust settings!
Press CTRL+C to exit.
""")
class SpaceInvader(MenuOption):
"""
A silly example "plug-in" showing an
animated space invader.
"""
def __init__(self):
self.start = self.millis()
self.invader = [[14, 31, 21, 31, 9, 18, 9, 18],
[14, 31, 21, 31, 18, 9, 18, 9]]
MenuOption.__init__(self)
def redraw(self, menu):
now = self.millis()
x = int((self.start - now) / 200 % 16)
menu.lcd.create_char(0, self.invader[int(
(self.start - now) / 400 % 2)])
menu.write_row(0, 'Space Invader!')
menu.write_row(1, (' ' * x) + chr(0))
menu.clear_row(2)
# Using a set of nested lists you can describe
# the menu you want to display on dot3k.
# Instances of classes derived from MenuOption can
# be used as menu items to show information or change settings.
# See GraphTemp, GraphCPU, Contrast and Backlight for examples.
my_invader = SpaceInvader()
menu = Menu(
structure={
'WiFi': Wlan(),
'Space Invader': my_invader,
'Clock': Clock(backlight),
'Status': {
'IP': IPAddress(),
'CPU': GraphCPU(backlight),
'Temp': GraphTemp()
},
'Settings': {
'Display': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
}
},
lcd=lcd,
idle_handler=my_invader,
idle_timeout=30,
input_handler=Text())
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.touch
"""
nav.bind_defaults(menu)
while 1:
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/advanced/demo.py | examples/dothat/advanced/demo.py | #!/usr/bin/env python
import math
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
print("""
This example gives a basic demo of Display-o-Tron HAT's features.
It will sweep the backlight, scan the bargraph and display text on screen!
Press CTRL+C to exit.
""")
pirate = [[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x16, 0x06, 0x00, 0x08, 0x03, 0x1e],
[0x00, 0x1f, 0x0b, 0x03, 0x00, 0x04, 0x11, 0x1f],
[0x00, 0x1f, 0x05, 0x01, 0x00, 0x02, 0x08, 0x07]]
heart = [[0x00, 0x0a, 0x1f, 0x1f, 0x1f, 0x0e, 0x04, 0x00],
[0x00, 0x00, 0x0a, 0x0e, 0x0e, 0x04, 0x00, 0x00],
[0x00, 0x00, 0x00, 0x0e, 0x04, 0x00, 0x00, 0x00],
[0x00, 0x00, 0x0a, 0x0e, 0x0e, 0x04, 0x00, 0x00]]
pacman = [[0x0e, 0x1f, 0x1d, 0x1f, 0x18, 0x1f, 0x1f, 0x0e],
[0x0e, 0x1d, 0x1e, 0x1c, 0x18, 0x1c, 0x1e, 0x0f]]
colours = [
"\x01 much red \x01", "\x01 very orange \x01",
"\x01 many yellow \x01", "\x01 also green \x01",
"\x01 such blue \x01", "\x01 so indigo \x01",
"\x01 ahoy voilet \x01"
]
lcd.set_cursor_position(0, 2)
lcd.set_cursor_position(0, 0)
lcd.write(chr(0) + " such rainbow!")
def get_anim_frame(char, fps):
return char[int(round(time.time() * fps) % len(char))]
x = 0
text = " pimoroni ftw "
while True:
x += 3
x %= 360
backlight.sweep((360.0 - x) / 360.0)
backlight.set_graph(abs(math.sin(x / 100.0)))
if x == 0:
lcd.set_cursor_position(0, 1)
lcd.write(" " * 16)
pos = int(x / 20)
lcd.set_cursor_position(0, 1)
lcd.write(text[:pos] + "\x02")
lcd.set_cursor_position(0, 2)
lcd.write(colours[int(x / 52)])
lcd.create_char(0, get_anim_frame(pirate, 2))
lcd.create_char(1, get_anim_frame(heart, 2))
lcd.create_char(2, get_anim_frame(pacman, 2))
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/advanced/radio.py | examples/dothat/advanced/radio.py | #!/usr/bin/env python
import sys
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
import dothat.touch as nav
from dot3k.menu import Menu
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.clock import Clock
from plugins.graph import GraphCPU, GraphTemp
from plugins.radio import Radio
from plugins.volume import Volume
from plugins.utils import Backlight, Contrast
print("""
This advanced example uses the menu framework.
Providing you have VLC and extra dependencies installed,
it should function as an internet radio!
Press CTRL+C to exit.
""")
nav.enable_repeat(True)
# We want to use clock both as an option
# and as the idle plugin
clock = Clock(backlight)
"""
Using a set of nested dictionaries you can describe
the menu you want to display on dot3k.
A nested dictionary describes a submenu.
An instance of a plugin class ( derived from MenuOption ) can
be used for things like settings, radio, etc
A function name will call that function.
"""
menu = Menu(
{
'Clock': clock,
'Radio Stream': Radio(),
'Volume': Volume(backlight),
'Status': {
'CPU': GraphCPU(),
'Temp': GraphTemp()
},
'Settings': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
},
lcd, # Draw to dot3k.lcd
clock, # Idle with the clock plugin,
10 # Idle after 10 seconds
)
"""
You can use anything to control dot3k.menu,
but you'll probably want to use dot3k.touch
"""
@nav.on(nav.UP)
def handle_up(ch, evt):
menu.up()
@nav.on(nav.CANCEL)
def handle_cancel(ch, evt):
menu.cancel()
@nav.on(nav.DOWN)
def handle_down(ch, evt):
menu.down()
@nav.on(nav.LEFT)
def handle_left(ch, evt):
menu.left()
@nav.on(nav.RIGHT)
def handle_right(ch, evt):
menu.right()
@nav.on(nav.BUTTON)
def handle_button(ch, evt):
menu.select()
while 1:
# Redraw the menu, since we don't want to hand this off to a thread
menu.redraw()
time.sleep(0.05)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/advanced/game.py | examples/dothat/advanced/game.py | #!/usr/bin/env python
import sys
import signal
import dothat.backlight as backlight
import dothat.lcd as lcd
import dothat.touch as nav
from dot3k.menu import Menu
# Add the root examples dir so Python can find the plugins
sys.path.append('../../')
from plugins.debris import Debris
from plugins.utils import Backlight, Contrast
print("""
This advanced example uses the menu framework.
It loads the debris game plugin. Your score is
time survived in seconds, see how well you can do!
Press CTRL+C to exit.
""")
# Build your menu!
menu = Menu({
'Debris Game': Debris(backlight),
'Settings': {
'Display': {
'Contrast': Contrast(lcd),
'Backlight': Backlight(backlight)
}
}
}, lcd)
# Hook captouch into menu with default settings
nav.bind_defaults(menu)
# Start the menu redraw loop
menu.run()
signal.pause()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/graph.py | examples/dothat/basic/graph.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
print("""
This example shows you how to take individual control of the bar graph LEDs.
You should see the bar graph LEDs count up in binary!
Press CTRL+C to exit.
""")
# Each LED can be either on/off,
# and brightness is controlled globally using:
# * graph_set_led_duty(min, max)
# When you don't need a bar graph, these LEDs could display
# remaining lives in a game, the status of different processes,
# the hour of the day in binary or anything else you might need!
lcd.set_cursor_position(0, 1)
lcd.write(" So Graph! ")
# Reset the LED states and polarity
backlight.graph_off()
# Dim the LEDs by setting the max duty to 1
backlight.graph_set_led_duty(0, 1)
# Now run a binary counter on the LEDs
while True:
for x in range(64):
for led in range(6):
backlight.graph_set_led_state(led, x & (1 << led))
time.sleep(0.1)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/ipaddr.py | examples/dothat/basic/ipaddr.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import fcntl
import socket
import struct
import dothat.lcd as lcd
def get_addr(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15].encode('utf-8')))[20:24])
except IOError:
return 'Not Found!'
wlan0 = get_addr('wlan0')
eth0 = get_addr('eth0')
host = socket.gethostname()
lcd.clear()
lcd.set_cursor_position(0, 0)
lcd.write('{}'.format(host))
lcd.set_cursor_position(0, 1)
if eth0 != 'Not Found!':
lcd.write(eth0)
else:
lcd.write('eth0 {}'.format(eth0))
lcd.set_cursor_position(0, 2)
if wlan0 != 'Not Found!':
lcd.write(wlan0)
else:
lcd.write('wlan0 {}'.format(wlan0))
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/touch.py | examples/dothat/basic/touch.py | #!/usr/bin/env python
import signal
import dothat.backlight as backlight
import dothat.lcd as lcd
import dothat.touch as nav
print("""
This example shows the Display-o-Tron HAT touch inputs in action.
Touch an input and you should see the LCD change accordingly.
Press CTRL+C to exit.
""")
"""
Captouch provides the @captouch.on() decorator
to make it super easy to attach handlers to each button.
It's also a drop-in replacement for joystick, with one exception:
it has a "cancel" method.
The handler will receive "channel" ( corresponding to a particular
button ID ) and "event" ( corresponding to press/release ) arguments.
"""
@nav.on(nav.UP)
def handle_up(ch, evt):
print("Up pressed!")
lcd.clear()
backlight.rgb(255, 0, 0)
lcd.write("Up up and away!")
@nav.on(nav.DOWN)
def handle_down(ch, evt):
print("Down pressed!")
lcd.clear()
backlight.rgb(0, 255, 0)
lcd.write("Down down doobie down!")
@nav.on(nav.LEFT)
def handle_left(ch, evt):
print("Left pressed!")
lcd.clear()
backlight.rgb(0, 0, 255)
lcd.write("Leftie left left!")
@nav.on(nav.RIGHT)
def handle_right(ch, evt):
print("Right pressed!")
lcd.clear()
backlight.rgb(0, 255, 255)
lcd.write("Rightie tighty!")
@nav.on(nav.BUTTON)
def handle_button(ch, evt):
print("Button pressed!")
lcd.clear()
backlight.rgb(255, 255, 255)
lcd.write("Ouch!")
@nav.on(nav.CANCEL)
def handle_cancel(ch, evt):
print("Cancel pressed!")
lcd.clear()
backlight.rgb(0, 0, 0)
lcd.write("Boom!")
# Prevent the script exiting!
signal.pause()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/room.py | examples/dothat/basic/room.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import atexit
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
print("""
This is a really experimental example that doesn't do much!
Do not adjust the horizontal, or the vertical!
Press CTRL+C to exit.
""")
rain = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 0, 2, 0, 0, 0, 0],
[0, 0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 0, 0, 4, 0, 0],
[0, 0, 0, 0, 0, 0, 8, 0], [0, 0, 0, 0, 0, 0, 0, 16],
[0, 0, 0, 0, 0, 0, 0, 0]]
def tidyup():
backlight.off()
lcd.clear()
def get_anim_frame(char, fps):
return char[int(round(time.time() * fps) % len(char))]
backlight.graph_off()
backlight.off()
lcd.set_cursor_position(0, 0)
lcd.write(chr(0) * 16)
lcd.set_cursor_position(0, 1)
lcd.write(chr(0) * 16)
lcd.set_cursor_position(0, 2)
lcd.write(chr(0) * 16)
time.sleep(1)
for x in range(0, 255, 5):
backlight.single_rgb(3, x, x, x)
atexit.register(tidyup)
while True:
lcd.create_char(0, get_anim_frame(rain, 20))
time.sleep(0.1)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/hello_world.py | examples/dothat/basic/hello_world.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import dothat.lcd as lcd
print("""
This example shows a basic "Hello World" on the LCD.
You should see "Hello World" displayed on your LCD!
Press CTRL+C to exit.
""")
# Clear the LCD and display Hello World
lcd.clear()
lcd.write("Hello World")
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/off.py | examples/dothat/basic/off.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This example clear the screen and turn
off all LED from the Display-o-Tron HAT """
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import dothat.backlight as backlight
import dothat.lcd as lcd
# Reset the LED states and polarity
backlight.graph_off()
# Empty the screen
lcd.clear()
# Turn off the backlight
backlight.rgb(0, 0, 0)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/backlight.py | examples/dothat/basic/backlight.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import math
import time
import dothat.backlight as backlight
import dothat.lcd as lcd
print("""
This example shows you a feature of the Dot HAT backlight.
You should see a rainbow sweep across the whole display!
Press CTRL+C to exit.
""")
lcd.set_cursor_position(0, 1)
lcd.write(" Such Rainbow! ")
x = 0
while True:
x += 1
backlight.sweep((x % 360) / 360.0)
backlight.set_graph(abs(math.sin(x / 100.0)))
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/dothat/basic/temp.py | examples/dothat/basic/temp.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from multiprocessing import Process
print("""
This example shows you a feature of the Dot HAT.
You should see the Temperature of your Raspberry Pi!
Press CTRL+C to exit.
""")
def temp():
print('Starting Temp')
from dothat import backlight
from dothat import lcd
import time
lcd.set_contrast(50)
while True:
tempC = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
# Change backlight if temp changes
if tempC < 60:
backlight.rgb(0, 255, 0)
elif tempC > 70:
backlight.rgb(255, 0, 0)
else:
backlight.rgb(0, 255, 255)
# Convert Temp to String
tempF = str(tempC)
# Write Temp and wait 1 sec.
lcd.set_cursor_position(0, 0)
lcd.write("Temp: " + tempF + " C")
time.sleep(1)
lcd.clear()
print('backlight: finishing')
def graph():
print('Starting Graph')
from dothat import backlight
import time
import math
x = 0
while True:
x += 1
backlight.set_graph(abs(math.sin(x / 100.0)))
time.sleep(0.01)
print('graph: finishing')
if __name__ == '__main__':
p1 = Process(target=temp)
p1.start()
p2 = Process(target=graph)
p2.start()
p1.join()
p2.join()
# Multithreading:
# ==============
# import threading
# p1 = threading.Thread(name='background', target=temp)
# p2 = threading.Thread(name='background', target=graph)
# p1.start()
# p2.start()
# Another way of doing parallel:
# =============================
# def runInParallel(*fns):
# proc = []
# for fn in fns:
# p = Process(target=fn)
# p.start()
# proc.append(p)
# for p in proc:
# p.join()
# runInParallel(func1, func2)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/utils/usbkeyboard.py | examples/utils/usbkeyboard.py | import threading
from sys import exit
try:
import usb.core
import usb.util
except ImportError:
exit("This script requires the pyusb module\nInstall with: sudo pip install pyusb")
class StoppableThread(threading.Thread):
"""Basic stoppable thread wrapper
Adds Event for stopping the execution loop and exiting cleanly."""
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
self.daemon = True
def start(self):
if not self.isAlive():
self.stop_event.clear()
threading.Thread.start(self)
def stop(self):
if self.isAlive():
# set event to signal thread to terminate
self.stop_event.set()
# block calling thread until thread really has terminated
self.join()
class AsyncWorker(StoppableThread):
"""Basic thread wrapper class for asyncronously running functions
Basic thread wrapper class for running functions asyncronously. Return False from your function to abort looping."""
def __init__(self, todo):
StoppableThread.__init__(self)
self.todo = todo
def run(self):
while not self.stop_event.is_set():
if self.todo() is False:
break
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
BUTTON = 'enter'
handlers = {}
directions = {
'up': 82,
'down': 81,
'left': 80,
'right': 79,
'enter': 40
}
dev = usb.core.find(idVendor=0x1997, idProduct=0x2433)
if dev is None:
exit('USB device not found!')
endpoint = dev[0][(0, 0)][0]
if dev.is_kernel_driver_active(0) is True:
dev.detach_kernel_driver(0)
usb.util.claim_interface(dev, 0)
def on(button, bouncetime=0):
def register(handler):
handlers[button] = handler
return register
def repeat(button, handler, delay, speed):
pass
def poll():
control = None
try:
control = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
except:
pass
if control:
for direction in directions.keys():
if directions[direction] in control:
if direction in handlers.keys():
handlers[direction](directions[direction])
p = AsyncWorker(poll)
p.start()
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/utils/__init__.py | examples/utils/__init__.py | python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false | |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/graph.py | examples/plugins/graph.py | import fcntl
import socket
import struct
import subprocess
import time
from sys import exit
try:
import psutil
except ImportError:
exit("This library requires the psutil module\nInstall with: sudo pip install psutil")
from dot3k.menu import MenuOption
def run_cmd(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]
return output
class IPAddress(MenuOption):
"""
A plugin which gets the IP address for wlan0
and eth0 and displays them on the screen.
"""
def __init__(self):
self.mode = 0
self.wlan0 = self.get_addr('wlan0')
self.eth0 = self.get_addr('eth0')
self.is_setup = False
MenuOption.__init__(self)
def get_addr(self, ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15].encode('utf-8'))
)[20:24])
except IOError:
return 'Not Found!'
def redraw(self, menu):
if not self.is_setup:
menu.lcd.create_char(0, [0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
self.is_setup = True
menu.write_row(0, 'IP Address')
if self.mode == 0:
menu.write_row(1, chr(0) + ' Wired:')
menu.write_row(2, self.eth0)
else:
menu.write_row(1, chr(0) + ' Wireless:')
menu.write_row(2, self.wlan0)
def down(self):
self.mode = 1
def up(self):
self.mode = 0
def left(self):
return False
def cleanup(self):
self.is_setup = False
class GraphCPU(MenuOption):
"""
A simple "plug-in" example, this gets the CPU load
and draws it to the LCD when active
"""
def __init__(self, backlight=None):
self.backlight = backlight
self.cpu_samples = [0, 0, 0, 0, 0]
self.cpu_avg = 0
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
now = self.millis()
if now - self.last < 1000:
return false
self.cpu_samples.append(psutil.cpu_percent())
self.cpu_samples.pop(0)
self.cpu_avg = sum(self.cpu_samples) / len(self.cpu_samples)
self.cpu_avg = round(self.cpu_avg * 100.0) / 100.0
menu.write_row(0, 'CPU Load')
menu.write_row(1, str(self.cpu_avg) + '%')
menu.write_row(2, '#' * int(16 * (self.cpu_avg / 100.0)))
if self.backlight is not None:
self.backlight.set_graph(self.cpu_avg / 100.0)
def left(self):
if self.backlight is not None:
self.backlight.set_graph(0)
return False
class GraphTemp(MenuOption):
"""
A simple "plug-in" example, this gets the Temperature
and draws it to the LCD when active
"""
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def get_cpu_temp(self):
tempFile = open("/sys/class/thermal/thermal_zone0/temp")
cpu_temp = tempFile.read()
tempFile.close()
return float(cpu_temp) / 1000
def get_gpu_temp(self):
proc = subprocess.Popen(['/opt/vc/bin/vcgencmd', 'measure_temp'], stdout=subprocess.PIPE)
out, err = proc.communicate()
out = out.decode('utf-8')
gpu_temp = out.replace('temp=', '').replace('\'C', '')
return float(gpu_temp)
def redraw(self, menu):
now = self.millis()
if now - self.last < 1000:
return False
menu.write_row(0, 'Temperature')
menu.write_row(1, 'CPU:' + str(self.get_cpu_temp()))
menu.write_row(2, 'GPU:' + str(self.get_gpu_temp()))
class GraphNetTrans(MenuOption):
"""
Gets the total transferred amount of the raspberry and displays to the LCD, ONLY on eth0.
"""
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def get_down(self):
show_dl_raw = ""
show_dl_hr = "ifconfig eth0 | grep bytes | cut -d')' -f1 | cut -d'(' -f2"
hr_dl = run_cmd(show_dl_hr)
return hr_dl
def get_up(self):
show_ul_raw = ""
show_ul_hr = "ifconfig eth0 | grep bytes | cut -d')' -f2 | cut -d'(' -f2"
hr_ul = run_cmd(show_ul_hr)
return hr_ul
def redraw(self, menu):
now = self.millis()
if now - self.last < 1000:
return false
menu.write_row(0, 'ETH0 Transfers')
menu.write_row(1, str('Dn:' + self.get_down())[:-1])
menu.write_row(2, str('Up:' + self.get_up())[:-1])
class GraphNetSpeed(MenuOption):
"""
Gets the total network transferred amount of the raspberry and displays to the LCD, ONLY on eth0.
"""
def __init__(self):
self.last = self.millis()
self.last_update = 0
self.raw_dlold = 0
self.raw_ulold = 0
self.dlspeed = 0
self.ulspeed = 0
self.iface = 'eth0'
MenuOption.__init__(self)
def get_current_down(self, iface='eth0'):
show_dl_raw = "ifconfig " + iface + " | grep bytes | cut -d':' -f2 | cut -d' ' -f1"
raw_dl = run_cmd(show_dl_raw)
return raw_dl[:-1]
def get_current_up(self, iface='eth0'):
show_ul_raw = "ifconfig " + iface + " | grep bytes | cut -d':' -f3 | cut -d' ' -f1"
raw_ul = run_cmd(show_ul_raw)
return raw_ul[:-1]
def up(self):
self.iface = 'eth0'
def down(self):
self.iface = 'wlan0'
def redraw(self, menu):
if self.millis() - self.last_update > 1000:
tdelta = self.millis() - self.last_update
self.last_update = self.millis()
raw_dlnew = self.get_current_down(self.iface)
raw_ulnew = self.get_current_up(self.iface)
self.dlspeed = 0
self.ulspeed = 0
try:
ddelta = int(raw_dlnew) - int(self.raw_dlold)
udelta = int(raw_ulnew) - int(self.raw_ulold)
self.dlspeed = round(float(ddelta) / float(tdelta), 1)
self.ulspeed = round(float(udelta) / float(tdelta), 1)
except ValueError:
pass
self.raw_dlold = raw_dlnew
self.raw_ulold = raw_ulnew
menu.write_row(0, self.iface + ' Speed')
menu.write_row(1, str('Dn:' + str(self.dlspeed) + 'kB/s'))
menu.write_row(2, str('Up:' + str(self.ulspeed) + 'kB/s'))
class GraphSysShutdown(MenuOption):
"""Shuts down the Raspberry Pi"""
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
shutdown = "sudo shutdown -h now"
now = self.millis()
if now - self.last < 1000 * 5:
return False
a = run_cmd(shutdown)
menu.write_row(0, 'RPI Shutdown')
menu.write_row(1, '')
menu.write_row(2, time.strftime(' %a %H:%M:%S '))
class GraphSysReboot(MenuOption):
"""Reboots the Raspberry Pi"""
def __init__(self):
self.last = self.millis()
MenuOption.__init__(self)
def redraw(self, menu):
reboot = "sudo reboot"
now = self.millis()
if now - self.last < 1000 * 5:
return False
a = run_cmd(reboot)
menu.write_row(0, 'RPI Reboot')
menu.write_row(1, '')
menu.write_row(2, time.strftime(' %a %H:%M:%S '))
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/volume.py | examples/plugins/volume.py | import os
import subprocess
import time
from sys import version_info
import dot3k.backlight
from dot3k.menu import MenuIcon
from dot3k.menu import MenuOption
MODE_AUTO = 0
MODE_HEADPHONES = 1
MODE_HDMI = 2
EDIT_VOLUME = 0
EDIT_OUTPUT = 1
EDIT_EXIT = 2
class Volume(MenuOption):
def __init__(self, backlight=None):
MenuOption.__init__(self)
self.output_options = {
MODE_AUTO: 'Auto',
MODE_HEADPHONES: 'Headphones',
MODE_HDMI: 'HDMI'
}
self.output_mode = -1
self.volume = None
self.backlight = backlight
self.actual_volume = 0
self.last_update = 0
self.edit_mode = EDIT_VOLUME
self._icons_setup = False
def setup(self, config):
MenuOption.setup(self, config)
self.edit_mode = EDIT_VOLUME
self.volume = int(self.get_option('Sound', 'volume', 80))
self.set_volume()
self.actual_volume = self.get_volume()
self.output_mode = self.get_mode()
def setup_icons(self, menu):
menu.lcd.create_char(0, MenuIcon.arrow_left_right) # Left/right arrow
menu.lcd.create_char(1, MenuIcon.arrow_up_down) # Up/Down arrow
menu.lcd.create_char(2, MenuIcon.back)
menu.lcd.create_char(3, MenuIcon.arrow_left)
menu.lcd.create_char(4, MenuIcon.bar_left)
menu.lcd.create_char(5, MenuIcon.bar_right)
menu.lcd.create_char(6, MenuIcon.bar_full)
menu.lcd.create_char(7, MenuIcon.bar_empty)
self._icons_setup = True
def cleanup(self):
self._icons_setup = False
dot3k.backlight.set_graph(0)
def down(self):
self.edit_mode += 1
self.edit_mode %= 3
def left(self):
if self.backlight is not None:
self.backlight.set_graph(0)
return False
def up(self):
self.edit_mode -= 1
self.edit_mode %= 3
return True
def get_mode(self):
mode = subprocess.check_output("amixer cget numid=3 | grep ': values='", shell=True)
mode = mode.decode().split('=')[1]
return int(mode)
def set_mode(self):
subprocess.check_output("amixer cset numid=3 " + str(self.output_mode), shell=True)
def get_volume(self):
actual_volume = subprocess.check_output("amixer sget 'PCM' | grep 'Left:' | awk -F'[][]' '{ print $2 }'", shell=True)
if version_info[0] >= 3:
actual_volume = actual_volume.strip().decode('utf-8')
else:
actual_volume = actual_volume.strip()
actual_volume = actual_volume[:2]
return float(actual_volume)
def cleanup(self):
if self.backlight is not None:
self.backlight.set_graph(0)
def set_volume(self):
self.set_option('Sound', 'volume', str(self.volume))
devnull = open(os.devnull, 'w')
subprocess.call(['/usr/bin/amixer', 'sset', "'PCM'", str(self.volume) + '%'], stdout=devnull)
self.actual_volume = self.get_volume()
time.sleep(0.01)
def left(self):
if self.edit_mode == EDIT_VOLUME:
self.volume -= 1
if self.volume < 0:
self.volume = 0
self.set_volume()
elif self.edit_mode == EDIT_OUTPUT:
self.output_mode += 1
self.output_mode %= 3
self.set_mode()
elif self.edit_mode == EDIT_EXIT:
return False
return True
def right(self):
if self.edit_mode == EDIT_VOLUME:
self.volume += 1
if self.volume > 100:
self.volume = 100
self.set_volume()
elif self.edit_mode == EDIT_OUTPUT:
self.output_mode -= 1
self.output_mode %= 3
self.set_mode()
def redraw(self, menu):
if not self._icons_setup:
self.setup_icons(menu)
if self.edit_mode == EDIT_VOLUME:
vol_bar = int(14.0 * float(self.actual_volume) / 100.0)
menu.write_row(0, chr(1) + ' Change Volume')
menu.write_row(1, ' ' + chr(0) + 'Volume: ' + str(self.volume))
menu.write_row(2, chr(4) + (chr(6) * vol_bar) + (chr(7) * (14 - vol_bar)) + chr(5))
elif self.edit_mode == EDIT_OUTPUT:
menu.write_row(0, chr(1) + ' Audio Output')
menu.write_row(1, ' ' + chr(0) + self.output_options[self.output_mode])
menu.clear_row(2)
elif self.edit_mode == EDIT_EXIT:
menu.write_row(0, chr(1) + ' Done?')
menu.write_row(1, ' ' + chr(3) + 'Exit')
menu.clear_row(2)
if self.millis() - self.last_update > 1000:
self.actual_volume = self.get_volume()
self.last_update = self.millis()
if self.backlight is not None:
self.backlight.set_graph(float(self.actual_volume) / 100.0)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/stocks.py | examples/plugins/stocks.py | """
Stocks plugin, ported from Facelessloser's Atmega_screen
https://github.com/facelessloser/Atmega_screen/blob/master/arduino_python_files/stock-ticker/atmega_screen_stock_ticker.py
"""
import json
import threading
import urllib
from dot3k.menu import MenuOption
class Stocks(MenuOption):
def __init__(self):
self.companies = ['GOOG', 'AAPL', 'TWTR', 'FB']
self.data = {}
self.company = 0
self.last_update = 0
self.last_event = 0
MenuOption.__init__(self)
self.is_setup = False
def input_prompt(self):
"""
Returns the prompt/title for the input plugin
"""
return 'Stock code:'
def receive_input(self, value):
"""
The value we get back when text input finishes
"""
self.companies.append(value)
self.get_stock_data(True)
self.update_options()
def begin(self):
self.reset_timeout()
def add_new(self):
self.request_input()
def reset_timeout(self):
self.last_event = self.millis()
def setup(self, config):
MenuOption.setup(self, config)
self.load_options()
def update_options(self):
self.set_option('Stocks', 'companies', ','.join(self.companies))
pass
def load_options(self):
self.companies = self.get_option('Stocks', 'companies', ','.join(self.companies)).split(',')
pass
def cleanup(self):
self.is_setup = False
def select(self):
self.add_new()
return False
def left(self):
self.reset_timeout()
return False
def right(self):
self.reset_timeout()
return True
def up(self):
self.reset_timeout()
self.company = (self.company - 1) % len(self.companies)
return True
def down(self):
self.reset_timeout()
self.company = (self.company + 1) % len(self.companies)
return True
def get_stock_data(self, force=False):
# Update only once every 60 seconds
if self.millis() - self.last_update < 6 * 1000 * 60 and not force:
return False
update = threading.Thread(None, self.do_update)
update.daemon = True
update.start()
def do_update(self):
self.last_update = self.millis()
base_url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22{STOCK}%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json'
for company in self.companies:
url_open = urllib.urlopen(base_url.replace('{STOCK}', company))
url_read = url_open.read()
parsed_json = json.loads(url_read)
self.data[company] = (
float(parsed_json['query']['results']['quote']['LastTradePriceOnly']),
float(parsed_json['query']['results']['quote']['PercentChange'].replace('%', '')),
float(parsed_json['query']['results']['quote']['MarketCapitalization'].replace('B', ''))
)
def redraw(self, menu):
self.get_stock_data()
if self.millis() - self.last_event >= 6 * 1000 * 5:
self.company = (self.millis() / 5000) % len(self.companies)
if not self.is_setup:
menu.lcd.create_char(0, [0, 0, 0, 14, 17, 17, 14, 0])
menu.lcd.create_char(1, [0, 0, 0, 14, 31, 31, 14, 0])
menu.lcd.create_char(2, [0, 14, 17, 17, 17, 14, 0, 0])
menu.lcd.create_char(3, [0, 14, 31, 31, 31, 14, 0, 0])
menu.lcd.create_char(4, [0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.is_setup = True
current_company = self.companies[self.company]
menu.write_row(0, current_company)
if current_company in self.data.keys():
data = self.data[current_company]
menu.write_row(1, str(data[0]) + ' ' + chr(4) + str(data[1]) + '%')
menu.write_row(2, 'Cap:' + str(data[2]) + 'B')
else:
menu.write_row(1, 'No Data Available')
menu.write_row(2, '')
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/transmission.py | examples/plugins/transmission.py | """
Plugin for Transmission torrent client.
Requires Transmission install: sudo apt-get install transmission-daemon
You'll probably also want the command-line client: transmission-cli so you can add and manage torrents.
Auth isn't supported at the moment, so you'll have to:
sudo service transmission-daemon stop
sudo vim /etc/transmission-daemon/settings.json
Find the setting rpc-authentication-required and make sure it's set to false.
Support for pausing/resuming torrents is planned.
"""
import threading
import dot3k.backlight
from dot3k.menu import MenuOption
class Transmission(MenuOption):
def __init__(self):
self.host = 'localhost'
self.port = 9091
self.client = None
self.items = []
self.selected_item = 0
self.last_update = 0
self.updating = False
self.last_event = 0
MenuOption.__init__(self)
self.is_setup = False
self.auto_cycle_timeout = 10000 # Start auto advancing after n/1000 sec of no user interaction
self.auto_cycle_speed = 10000 # Time between advances
def begin(self):
self.reset_timeout()
self.update(True)
def connect(self):
try:
import transmissionrpc
except ImportError:
print("Transmission requires transmissionrpc")
print("please: sudo pip install transmissionrpc")
return
self.client = transmissionrpc.Client(self.host, self.port)
def reset_timeout(self):
self.last_event = self.millis()
def setup(self, config):
MenuOption.setup(self, config)
self.load_options()
self.connect()
def update_options(self):
pass
def load_options(self):
self.host = self.get_option('Transmission', 'host', self.host)
self.port = int(self.get_option('Transmission', 'port', self.port))
def cleanup(self):
self.is_setup = False
def select(self):
self.add_new()
return False
def left(self):
self.reset_timeout()
return False
def right(self):
self.reset_timeout()
return True
def up(self):
self.reset_timeout()
self.selected_item = (self.selected_item - 1) % len(self.items)
return True
def down(self):
self.reset_timeout()
self.selected_item = (self.selected_item + 1) % len(self.items)
return True
def update(self, force=False):
# Update only once every 30 seconds
if self.millis() - self.last_update < 1000 * 30 and not force:
return False
self.last_update = self.millis()
update = threading.Thread(None, self.do_update)
update.daemon = True
update.start()
def do_update(self):
if self.updating or self.client == None:
return False
self.updating = True
torrents = self.client.get_torrents()
for torrent in torrents:
size = 0
for idx in torrent.files():
size += torrent.files()[idx]['size']
size = round(size / 1000.0 / 1000.0 * 10) / 10
torrent.size = size
if self.selected_item > len(torrents):
self.selected_item = 0
self.reset_timeout()
self.items = torrents
self.updating = False
def redraw(self, menu):
self.update()
if self.millis() - self.last_event >= self.auto_cycle_timeout and len(self.items):
self.selected_item = ((
self.millis() - self.last_event - self.auto_cycle_timeout) / self.auto_cycle_speed) % len(
self.items)
if not self.is_setup:
menu.lcd.create_char(0, [0, 24, 30, 31, 30, 24, 0, 0]) # Play
menu.lcd.create_char(1, [0, 27, 27, 27, 27, 27, 0, 0]) # Pause
menu.lcd.create_char(4, [0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.is_setup = True
if len(self.items):
item = self.items[self.selected_item]
done = (item.size / 100.0) * item.progress
menu.write_option(row=0, icon=(chr(1) if item.status == 'stopped' else chr(0)), text=item.name, scroll=True)
menu.write_option(row=1, icon='', margin=0, text=str(done) + 'MB / ' + str(item.size) + 'MB', scroll=True)
menu.write_row(2, '')
dot3k.backlight.set_graph(item.progress / 100.0)
else:
menu.write_row(0, "No Torrents!")
menu.clear_row(1)
menu.clear_row(2)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/deluge.py | examples/plugins/deluge.py | """
Plugin for Deluge torrent client.
Requires deluge install: sudo apt-get install deluged deluged-console
"""
import subprocess
import threading
import dot3k.backlight
from dot3k.menu import MenuOption
class Deluge(MenuOption):
def __init__(self):
self.items = []
self.selected_item = 0
self.last_update = 0
self.updating = False
self.last_event = 0
MenuOption.__init__(self)
self.is_setup = False
self.auto_cycle_timeout = 10000 # Start auto advancing after n/1000 sec of no user interaction
self.auto_cycle_speed = 10000 # Time between advances
def begin(self):
self.reset_timeout()
self.update(True)
def reset_timeout(self):
self.last_event = self.millis()
def setup(self, config):
MenuOption.setup(self, config)
self.load_options()
def update_options(self):
pass
def load_options(self):
pass
def cleanup(self):
self.is_setup = False
def select(self):
self.add_new()
return False
def left(self):
self.reset_timeout()
return False
def right(self):
self.reset_timeout()
return True
def up(self):
self.reset_timeout()
self.selected_item = (self.selected_item - 1) % len(self.items)
return True
def down(self):
self.reset_timeout()
self.selected_item = (self.selected_item + 1) % len(self.items)
return True
def update(self, force=False):
# Update only once every 30 seconds
if self.millis() - self.last_update < 1000 * 30 and not force:
return False
self.last_update = self.millis()
update = threading.Thread(None, self.do_update)
update.daemon = True
update.start()
def do_update(self):
if self.updating:
return False
self.updating = True
torrents = subprocess.check_output('su pi -c "deluge-console info"', shell=True)
torrents = torrents.strip().split('\n \n')
torrents = map(lambda x: dict(y.split(': ', 1) for y in x),
map(lambda x: x.replace(' Active:', '\nActive:').replace(' Ratio:', '\nRatio:').split('\n'),
torrents))
for torrent in torrents:
if 'Progress' in torrent.keys():
torrent['Progress'] = float(torrent['Progress'].split('%')[0])
else:
torrent['Progress'] = 100.0
if self.selected_item > len(torrents):
self.selected_item = 0
self.reset_timeout()
self.items = torrents
self.updating = False
def redraw(self, menu):
self.update()
if self.millis() - self.last_event >= self.auto_cycle_timeout and len(self.items):
self.selected_item = ((
self.millis() - self.last_event - self.auto_cycle_timeout) / self.auto_cycle_speed) % len(
self.items)
if not self.is_setup:
menu.lcd.create_char(0, [0, 24, 30, 31, 30, 24, 0, 0]) # Play
menu.lcd.create_char(1, [0, 27, 27, 27, 27, 27, 0, 0]) # Pause
menu.lcd.create_char(4, [0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.is_setup = True
if len(self.items):
item = self.items[self.selected_item]
menu.write_option(row=0, icon=(chr(1) if item['State'] == 'Paused' else chr(0)), text=item['Name'],
scroll=True)
menu.write_option(row=1, icon='', margin=0, text=item['Size'], scroll=True)
menu.write_row(2, item['Active'])
dot3k.backlight.set_graph(item['Progress'] / 100.0)
else:
menu.write_row(0, "No Torrents!")
menu.clear_row(1)
menu.clear_row(2)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/wlan.py | examples/plugins/wlan.py | """
Plugin for managing connections to wifi networks
"""
import subprocess
import threading
from sys import exit
try:
import wifi
except ImportError:
exit("This library requires the wifi module\n\
Install with: sudo pip install wifi")
from dot3k.menu import MenuOption
class Wlan(MenuOption):
def __init__(self, backlight=None, interface='wlan0'):
self.items = []
self.interface = interface
self.wifi_pass = ""
self.selected_item = 0
self.connecting = False
self.scanning = False
self.has_error = False
self.error_text = ""
self.backlight = backlight
MenuOption.__init__(self)
self.is_setup = False
def run_cmd(self, cmd):
result = subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = result.stdout.read().decode()
stderr = result.stderr.read().decode()
return (stdout, stderr)
# print("stdout >> ", stdout)
# print("stderr >> ", stderr)
def begin(self):
self.has_errror = False
def setup(self, config):
MenuOption.setup(self, config)
@staticmethod
def update_options():
pass
def cleanup(self):
if self.backlight is not None:
self.backlight.set_graph(0)
self.is_setup = False
self.has_error = False
@staticmethod
def select():
return True
@staticmethod
def left():
return False
def right(self):
self.connect()
return True
def up(self):
if len(self.items):
self.selected_item = (self.selected_item - 1) % len(self.items)
return True
def down(self):
if len(self.items):
self.selected_item = (self.selected_item + 1) % len(self.items)
return True
@property
def current_network(self):
if self.selected_item < len(self.items):
return self.items[self.selected_item]
return None
@staticmethod
def input_prompt():
return 'Password:'
def connect(self):
network = self.current_network
scheme = wifi.Scheme.find(self.interface, network.ssid)
if scheme is None:
self.request_input()
else:
print("Connecting to {}".format(self.current_network.ssid))
t = threading.Thread(None, self.perform_connection)
t.daemon = True
t.start()
@staticmethod
def initial_value():
return ""
def receive_input(self, value):
self.wifi_pass = value
print("Connecting to {}".format(self.current_network.ssid))
print("Using Password: \"{}\"".format(self.wifi_pass))
t = threading.Thread(None, self.perform_connection)
t.daemon = True
t.start()
def perform_connection(self):
self.connecting = True
network = self.current_network
scheme = wifi.Scheme.find(self.interface, network.ssid)
new = False
if scheme is None:
new = True
scheme = wifi.Scheme.for_cell(
self.interface, network.ssid, network, passkey=self.wifi_pass)
scheme.save()
try:
scheme.activate()
except wifi.scheme.ConnectionError as e:
self.error('Connection Failed!')
print(e)
self.connecting = False
if new:
scheme.delete()
return
self.connecting = False
def clear_error(self):
self.has_error = False
self.error_text = ""
def error(self, text):
self.has_error = True
self.error_text = text
def scan(self):
update = threading.Thread(None, self.do_scan)
update.daemon = True
update.start()
def do_scan(self):
if self.scanning:
return False
self.scanning = True
result = self.run_cmd(["sudo ifup {}".format(self.interface)])
if "Ignoring unknown interface" in result[1]:
self.error("{} not found!".format(self.interface))
self.scanning = False
return
try:
result = wifi.scan.Cell.all(self.interface)
self.items = list(result)
print(self.items)
except wifi.scan.InterfaceError as e:
self.error("Interface Error!")
print(e)
self.scanning = False
def redraw(self, menu):
if self.has_error:
menu.write_option(row=0, text='Error:')
menu.write_option(row=1, text=self.error_text)
menu.clear_row(2)
return True
if self.scanning:
menu.clear_row(0)
menu.write_option(row=1, text='Scanning...')
menu.clear_row(2)
return True
if self.connecting:
menu.clear_row(0)
menu.write_option(row=1, text='Connecting...')
menu.clear_row(2)
return True
if not self.is_setup:
menu.lcd.create_char(0, [0, 24, 30, 31, 30, 24, 0, 0]) # Play
menu.lcd.create_char(1, [0, 27, 27, 27, 27, 27, 0, 0]) # Pause
menu.lcd.create_char(4,
[0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(
5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.scan()
self.is_setup = True
if self.current_network is not None:
item = self.current_network
status = 'Open'
if item.encrypted:
status = 'Secured: ' + str(item.encryption_type)
menu.write_option(row=0, text=str(item.ssid), scroll=True)
menu.write_option(row=1, icon='', text=status, scroll=True)
menu.write_option(
row=2, text='CH' + str(item.channel) + ' ' + item.frequency)
signal = float(item.quality.split('/')[0])
noise = float(item.quality.split('/')[1])
if self.backlight is not None:
self.backlight.set_graph(signal / noise)
else:
menu.clear_row(0)
menu.write_row(1, "No networks found!")
menu.clear_row(2)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/debris.py | examples/plugins/debris.py | import random
import time
from dot3k.menu import MenuOption
class Debris(MenuOption):
def __init__(self, backlight=None):
if backlight is None:
import dot3k.backlight
self.backlight = dot3k.backlight
else:
self.backlight = backlight
self.debug = False
self.star_seed = 'thestarsmydestination'
self.debris_seed = 'piratemonkeyrobotninja'
self.debris = []
self.stars = []
self.running = False
self.max_debris = 10
self.max_stars = 10
self.last_update = 0
self.time_start = 0
self.sprites = [
[14, 31, 31, 14, 0, 0, 0, 0], # 0: Debris top of char
[0, 0, 0, 0, 14, 31, 31, 14], # 1: Debris bottom of char
[30, 5, 7, 30, 0, 0, 0, 0], # 2: Ship top of char
[0, 0, 0, 0, 30, 5, 7, 30], # 3: Ship bottom of char
[30, 5, 7, 30, 14, 31, 31, 14], # 4: Ship above debris
[14, 31, 31, 14, 30, 5, 7, 30], # 5: Ship below debris
[0, 14, 31, 31, 31, 31, 14, 0] # 6: Giant debris
]
self.width = 16
self.height = 5 # Two rows per char
self.player_x = 1 # Player horizontal position
self.player_y = 3 # Player vertical position
self.current_player_x = None
self.current_player_y = None
self.current_player_pos = None
self.fill_debris()
MenuOption.__init__(self)
def begin(self):
self.running = False
self.reset()
self.backlight.hue(0.0)
def reset(self):
self.player_x = 1
self.player_y = 3
self.fill_debris()
self.fill_stars()
self.running = True
self.time_start = 0
self.last_update = 0
def fill_stars(self):
random.seed(self.star_seed)
self.stars = []
while len(self.stars) < self.max_stars:
new = (random.randint(0, 15), random.randint(0, 2))
if not new in self.stars:
self.stars.append(new)
def fill_debris(self):
random.seed(self.debris_seed)
self.debris = []
while len(self.debris) < self.max_debris:
new = (random.randint(5, 15), random.randint(0, self.height))
if not new in self.debris:
self.debris.append(new)
print(self.debris)
def left(self):
if not self.running:
r = int(self.get_option('Backlight', 'r'))
g = int(self.get_option('Backlight', 'g'))
b = int(self.get_option('Backlight', 'b'))
self.backlight.rgb(r, g, b)
return False
self.player_x -= 1
if self.player_x < 0:
self.player_x = 0
return True
def right(self):
if not self.running:
self.reset()
return True
self.player_x += 1
if self.player_x > 15:
self.player_x = 15
return True
def up(self):
self.player_y -= 1
if self.player_y < 0:
self.player_y = 0
if self.debug:
print("Player up", self.player_y)
return True
def down(self):
self.player_y += 1
if self.player_y > self.height:
self.player_y = self.height - 1
if self.debug:
print("Player down", self.player_y)
return True
def update(self, menu):
if self.time_start == 0:
for idx, sprite in enumerate(self.sprites):
menu.lcd.create_char(idx, sprite)
menu.clear_row(0)
menu.clear_row(1)
menu.clear_row(2)
for x in range(3):
menu.lcd.set_cursor_position(5, 1)
menu.lcd.write(' 0' + str(3 - x) + '! ')
time.sleep(0.5)
self.backlight.hue(0.5)
self.time_start = self.millis()
# Move all stars left
for idx, star in enumerate(self.stars):
self.stars[idx] = (star[0] - 0.5, star[1])
# Move all debris left 1 place
for idx, rock in enumerate(self.debris):
self.debris[idx] = (rock[0] - 1, rock[1])
debris_x = int(rock[0])
debris_y = int(rock[1])
if debris_x < 0:
continue
if debris_x == self.player_x and debris_y == self.player_y:
# Boom!
menu.lcd.set_cursor_position(5, 1)
menu.lcd.write(' BOOM!')
if self.debug:
print(debris_x, debris_y)
print(self.player_x, self.player_y)
exit()
self.running = False
return False
# Remove off-screen debris
self.debris = list(filter(lambda x: x[0] > -1, self.debris))
# Remove off-screen stars
self.stars = list(filter(lambda x: x[0] > -1, self.stars))
# Create new debris to replace the removed ones
while len(self.debris) < self.max_debris:
self.debris.append((15, random.randint(0, self.height)))
while len(self.stars) < self.max_stars:
self.stars.append((15, random.randint(0, 2)))
return True
def redraw(self, menu):
if not self.running:
return False
if self.millis() - self.last_update >= 250:
if not self.update(menu):
return False
self.last_update = self.millis()
game_time = str(int((self.millis() - self.time_start) / 1000)).zfill(3)
self.backlight.sweep(
((self.millis() - self.time_start) / 500 % 360) / 359.0)
buffer = []
for i in range(3):
buffer.append([' '] * 16)
for idx, rock in enumerate(self.stars):
buffer[rock[1]][int(rock[0])] = '.'
player_v = (self.player_y % 2)
buffer[int(self.player_y / 2)][self.player_x] = chr(2 + player_v)
for idx, rock in enumerate(self.debris):
debris_x = int(rock[0])
debris_y = int(rock[1])
debris_v = (debris_y % 2)
debris_sprite = debris_v
if int(debris_y / 2) == int(
self.player_y /
2) and debris_x == self.player_x and debris_v != player_v:
debris_sprite = 4 + player_v
current = buffer[int(debris_y / 2)][debris_x]
if current == chr(0) or current == chr(1):
debris_sprite = 6 # Giant Debris!
buffer[int(debris_y / 2)][debris_x] = chr(debris_sprite)
# Draw elapsed seconds
buffer[0][16 - len(game_time):len(game_time)] = game_time
for idx, row in enumerate(buffer):
menu.write_row(idx, ''.join(row))
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/utils.py | examples/plugins/utils.py | import colorsys
from dot3k.menu import MenuIcon
from dot3k.menu import MenuOption
class Backlight(MenuOption):
def __init__(self, backlight):
self.backlight = backlight
self.hue = 0
self.sat = 100
self.val = 100
self.mode = 0
self.r = 0
self.g = 0
self.b = 0
self.modes = ['h', 's', 'v', 'r', 'g', 'b', 'e']
self.from_hue()
self._icons_setup = False
MenuOption.__init__(self)
def from_hue(self):
rgb = colorsys.hsv_to_rgb(self.hue, self.sat / 100.0, self.val / 100.0)
self.r = int(255 * rgb[0])
self.g = int(255 * rgb[1])
self.b = int(255 * rgb[2])
def from_rgb(self):
self.hue = colorsys.rgb_to_hsv(self.r / 255.0, self.g / 255.0, self.b / 255.0)[0]
def setup(self, config):
self.config = config
self.mode = 0
self.r = int(self.get_option('Backlight', 'r', 255))
self.g = int(self.get_option('Backlight', 'g', 255))
self.b = int(self.get_option('Backlight', 'b', 255))
self.hue = float(self.get_option('Backlight', 'h', 0)) / 359.0
self.sat = int(self.get_option('Backlight', 's', 0))
self.val = int(self.get_option('Backlight', 'v', 100))
self.backlight.rgb(self.r, self.g, self.b)
def setup_icons(self, menu):
menu.lcd.create_char(0, MenuIcon.arrow_left_right)
menu.lcd.create_char(1, MenuIcon.arrow_up_down)
menu.lcd.create_char(2, MenuIcon.arrow_left)
self._icons_setup = True
def update_bl(self):
self.set_option('Backlight', 'r', str(self.r))
self.set_option('Backlight', 'g', str(self.g))
self.set_option('Backlight', 'b', str(self.b))
self.set_option('Backlight', 'h', str(int(self.hue * 359)))
self.set_option('Backlight', 's', str(self.sat))
self.set_option('Backlight', 'v', str(self.val))
self.backlight.rgb(self.r, self.g, self.b)
def down(self):
self.mode += 1
if self.mode >= len(self.modes):
self.mode = 0
return True
def up(self):
self.mode -= 1
if self.mode < 0:
self.mode = len(self.modes) - 1
return True
def right(self):
if self.mode == 6:
return False
if self.mode == 0:
self.hue += (1.0 / 359.0)
if self.hue > 1:
self.hue = 0
self.from_hue()
elif self.mode == 1: # sat
self.sat += 1
if self.sat > 100:
self.sat = 0
self.from_hue()
elif self.mode == 2: # val
self.val += 1
if self.val > 100:
self.val = 0
self.from_hue()
else: # rgb
if self.mode == 3: # r
self.r += 1
if self.r > 255:
self.r = 0
elif self.mode == 4: # g
self.g += 1
if self.g > 255:
self.g = 0
elif self.mode == 5: # b
self.b += 1
if self.b > 255:
self.b = 0
self.from_rgb()
self.update_bl()
return True
def left(self):
if self.mode == 0:
self.hue -= (1.0 / 359.0)
if self.hue < 0:
self.hue = 1
self.from_hue()
elif self.mode == 1: # sat
self.sat -= 1
if self.sat < 0:
self.sat = 100
self.from_hue()
elif self.mode == 2: # val
self.val -= 1
if self.val < 0:
self.val = 100
self.from_hue()
else: # rgb
if self.mode == 3: # r
self.r -= 1
if self.r < 0:
self.r = 255
elif self.mode == 4: # g
self.g -= 1
if self.g < 0:
self.g = 255
elif self.mode == 5: # b
self.b -= 1
if self.b < 0:
self.b = 255
self.from_rgb()
self.update_bl()
return True
def cleanup(self):
self._icons_setup = False
self.mode = 0
def redraw(self, menu):
if not self._icons_setup:
self.setup_icons(menu)
menu.write_row(0, chr(1) + 'Backlight')
if self.mode < 6:
row_1 = 'HSV: ' + str(int(self.hue * 359)).zfill(3) + ' ' + str(self.sat).zfill(3) + ' ' + str(
self.val).zfill(3)
row_2 = 'RGB: ' + str(self.r).zfill(3) + ' ' + str(self.g).zfill(3) + ' ' + str(self.b).zfill(3)
row_1 = list(row_1)
row_2 = list(row_2)
icon_char = 0
# Position the arrow
if self.mode == 0: # hue
row_1[4] = chr(icon_char)
elif self.mode == 1: # sat
row_1[8] = chr(icon_char)
elif self.mode == 2: # val
row_1[12] = chr(icon_char)
elif self.mode == 3: # r
row_2[4] = chr(icon_char)
elif self.mode == 4: # g
row_2[8] = chr(icon_char)
elif self.mode == 5: # b
row_2[12] = chr(icon_char)
menu.write_row(1, ''.join(row_1))
menu.write_row(2, ''.join(row_2))
else:
menu.write_row(1, chr(2) + 'Exit')
menu.clear_row(2)
class Contrast(MenuOption):
def __init__(self, lcd):
self.lcd = lcd
self.contrast = 30
self._icons_setup = False
MenuOption.__init__(self)
def right(self):
self.contrast += 1
if self.contrast > 63:
self.contrast = 0
self.update_contrast()
return True
def left(self):
self.contrast -= 1
if self.contrast < 0:
self.contrast = 63
self.update_contrast()
return True
def setup_icons(self, menu):
menu.lcd.create_char(0, MenuIcon.arrow_left_right)
menu.lcd.create_char(1, MenuIcon.arrow_up_down)
menu.lcd.create_char(2, MenuIcon.arrow_left)
self._icons_setup = True
def cleanup(self):
self._icons_setup = False
def setup(self, config):
self.config = config
self.contrast = int(self.get_option('Display', 'contrast', 40))
self.lcd.set_contrast(self.contrast)
def update_contrast(self):
self.set_option('Display', 'contrast', str(self.contrast))
self.lcd.set_contrast(self.contrast)
def redraw(self, menu):
if not self._icons_setup:
self.setup_icons(menu)
menu.write_row(0, 'Contrast')
menu.write_row(1, chr(0) + 'Value: ' + str(self.contrast))
menu.clear_row(2)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/clock.py | examples/plugins/clock.py | import time
from dot3k.menu import MenuOption
class Clock(MenuOption):
def __init__(self, backlight=None):
self.modes = ['date', 'week', 'binary', 'dim', 'bright']
self.mode = 0
self.binary = True
self.running = False
if backlight is None:
import dot3k.backlight
self.backlight = dot3k.backlight
else:
self.backlight = backlight
self.option_time = 0
self.dim_hour = 20
self.bright_hour = 8
self.is_setup = False
MenuOption.__init__(self)
def begin(self):
self.is_setup = False
self.running = True
def setup(self, config):
MenuOption.setup(self, config)
self.load_options()
def set_backlight(self, brightness):
brightness += 0.01
if brightness > 1.0:
brightness = 1.0
r = int(int(self.get_option('Backlight', 'r')) * brightness)
g = int(int(self.get_option('Backlight', 'g')) * brightness)
b = int(int(self.get_option('Backlight', 'b')) * brightness)
if self.backlight is not None:
self.backlight.rgb(r, g, b)
def update_options(self):
self.set_option('Clock', 'dim', str(self.dim_hour))
self.set_option('Clock', 'bright', str(self.bright_hour))
self.set_option('Clock', 'binary', str(self.binary))
def load_options(self):
self.dim_hour = int(
self.get_option('Clock', 'dim', str(self.dim_hour)))
self.bright_hour = int(
self.get_option('Clock', 'bright', str(self.bright_hour)))
self.binary = self.get_option('Clock', 'binary',
str(self.binary)) == 'True'
def cleanup(self):
self.running = False
time.sleep(0.01)
self.set_backlight(1.0)
self.is_setup = False
def left(self):
if self.modes[self.mode] == 'binary':
self.binary = False
elif self.modes[self.mode] == 'dim':
self.dim_hour = (self.dim_hour - 1) % 24
elif self.modes[self.mode] == 'bright':
self.bright_hour = (self.bright_hour - 1) % 24
else:
return False
self.update_options()
self.option_time = self.millis()
return True
def right(self):
if self.modes[self.mode] == 'binary':
self.binary = True
elif self.modes[self.mode] == 'dim':
self.dim_hour = (self.dim_hour + 1) % 24
elif self.modes[self.mode] == 'bright':
self.bright_hour = (self.bright_hour + 1) % 24
self.update_options()
self.option_time = self.millis()
return True
def up(self):
self.mode = (self.mode - 1) % len(self.modes)
self.option_time = self.millis()
return True
def down(self):
self.mode = (self.mode + 1) % len(self.modes)
self.option_time = self.millis()
return True
def redraw(self, menu):
if not self.running:
return False
if self.millis() - self.option_time > 5000 and self.option_time > 0:
self.option_time = 0
self.mode = 0
if not self.is_setup:
menu.lcd.create_char(0, [0, 0, 0, 14, 17, 17, 14, 0])
menu.lcd.create_char(1, [0, 0, 0, 14, 31, 31, 14, 0])
menu.lcd.create_char(2, [0, 14, 17, 17, 17, 14, 0, 0])
menu.lcd.create_char(3, [0, 14, 31, 31, 31, 14, 0, 0])
menu.lcd.create_char(4,
[0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(
5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.is_setup = True
hour = float(time.strftime('%H'))
brightness = 1.0
if hour > self.dim_hour:
brightness = 1.0 - (
(hour - self.dim_hour) / (24.0 - self.dim_hour))
elif hour < self.bright_hour:
brightness = 1.0 * (hour / self.bright_hour)
self.set_backlight(brightness)
menu.write_row(0, time.strftime(' %a %H:%M:%S '))
if self.binary:
binary_hour = str(
bin(int(time.strftime('%I'))))[2:].zfill(4).replace(
'0', chr(0)).replace('1', chr(1))
binary_min = str(
bin(int(time.strftime('%M'))))[2:].zfill(6).replace(
'0', chr(2)).replace('1', chr(3))
binary_sec = str(
bin(int(time.strftime('%S'))))[2:].zfill(6).replace(
'0', chr(0)).replace('1', chr(1))
menu.write_row(1, binary_hour + binary_min + binary_sec)
else:
menu.write_row(1, '-' * 16)
if self.idling:
menu.clear_row(2)
return True
bottom_row = ''
if self.modes[self.mode] == 'date':
bottom_row = time.strftime('%b %Y:%m:%d ')
elif self.modes[self.mode] == 'week':
bottom_row = time.strftime(' Week: %W')
elif self.modes[self.mode] == 'binary':
bottom_row = ' Binary ' + chr(5) + ('Y' if self.binary else 'N')
elif self.modes[self.mode] == 'dim':
bottom_row = ' Dim at ' + chr(5) + str(self.dim_hour).zfill(2)
elif self.modes[self.mode] == 'bright':
bottom_row = ' Bright at ' + chr(5) + str(
self.bright_hour).zfill(2)
menu.write_row(2, chr(4) + bottom_row)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/__init__.py | examples/plugins/__init__.py | python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false | |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/text.py | examples/plugins/text.py | from dot3k.menu import MenuOption
_MODE_CONFIRM = 1
_MODE_ENTRY = 0
class Text(MenuOption):
def __init__(self):
self.mode = _MODE_ENTRY
self.input_prompt = ''
self.initialized = False
self.back_icon = chr(0)
self.entry_char = 0
self.entry_mode = 0
self.entry_chars = [
list('\'|~+-_!?.0123456789' + self.back_icon + ' abcdefghijklmnopqrstuvwxyz' + self.back_icon),
list('"<>{}()[]:;/\^&*$%#' + self.back_icon + '@ABCDEFGHIJKLMNOPQRSTUVWXYZ' + self.back_icon)]
self.entry_text = [' '] * 16
self.confirm = 0
self.final_text = ''
self.entry_position = 0
MenuOption.__init__(self)
self.is_setup = False
def set_value(self, value):
length = len(value)
self.entry_text = list(value + self.back_icon + (' ' * (16 - length)))
self.entry_position = length
def set_prompt(self, value):
self.input_prompt = value
def get_value(self):
return self.final_text
def update_char(self):
self.entry_text[self.entry_position] = self.entry_chars[self.entry_mode][self.entry_char]
def change_case(self):
self.entry_mode = (self.entry_mode + 1) % len(self.entry_chars)
self.update_char()
def next_char(self):
self.entry_char = (self.entry_char + 1) % len(self.entry_chars[0])
self.update_char()
def prev_char(self):
self.entry_char = (self.entry_char - 1) % len(self.entry_chars[0])
self.update_char()
def pick_char(self, pick):
for x, chars in enumerate(self.entry_chars):
for y, char in enumerate(chars):
if char == pick:
self.entry_mode = x
self.entry_char = y
def prev_letter(self):
self.entry_position = (self.entry_position - 1) % len(self.entry_text)
self.pick_char(self.entry_text[self.entry_position])
def next_letter(self):
self.entry_position = (self.entry_position + 1) % len(self.entry_text)
self.pick_char(self.entry_text[self.entry_position])
def begin(self):
self.initialized = False
self.entry_char = 0
self.entry_mode = 0
self.entry_position = 0
self.mode = _MODE_ENTRY
self.pick_char(' ')
self.entry_text = [' '] * 16
self.set_value('')
def setup(self, config):
MenuOption.setup(self, config)
def cleanup(self):
self.entry_text = [' '] * 16
def left(self):
if self.mode == _MODE_CONFIRM:
self.confirm = (self.confirm + 1) % 3
return True
if self.entry_text[self.entry_position] == self.back_icon:
return True
self.prev_letter()
return True
def right(self):
if self.mode == _MODE_CONFIRM:
self.confirm = (self.confirm - 1) % 3
return True
if self.entry_text[self.entry_position] == self.back_icon:
return True
self.next_letter()
return True
def up(self):
if self.mode == _MODE_CONFIRM:
return True
self.prev_char()
return True
def down(self):
if self.mode == _MODE_CONFIRM:
return True
self.next_char()
return True
def select(self):
if self.mode == _MODE_CONFIRM:
if self.confirm == 1: # Yes
return True
elif self.confirm == 2: # Quit
self.cancel_input = True
self.mode = _MODE_ENTRY
return True
else: # No
self.mode = _MODE_ENTRY
return False
if self.entry_text[self.entry_position] == self.back_icon:
text = ''.join(self.entry_text)
self.final_text = text[0:text.index(self.back_icon)].strip()
self.mode = _MODE_CONFIRM
else:
self.change_case()
return False
def redraw(self, menu):
if not self.initialized:
menu.lcd.create_char(0, [0, 8, 30, 9, 1, 1, 14, 0]) # Back icon
menu.lcd.create_char(4, [0, 4, 14, 0, 0, 14, 4, 0]) # Up down arrow
menu.lcd.create_char(5, [0, 0, 10, 27, 10, 0, 0, 0]) # Left right arrow
self.initialized = True
if self.mode == _MODE_ENTRY:
menu.write_row(0, self.input_prompt)
menu.write_row(1, ''.join(self.entry_text))
if self.entry_text[self.entry_position] == self.back_icon:
if self.entry_position > 3:
menu.write_row(2, (' ' * (self.entry_position - 3)) + 'END' + chr(4))
else:
menu.write_row(2, (' ' * self.entry_position) + chr(4) + 'END')
else:
menu.write_row(2, (' ' * self.entry_position) + chr(4))
else:
menu.write_row(0, 'Confirm?')
menu.write_row(1, self.final_text)
menu.write_row(2,
' ' + ('>' if self.confirm == 1 else ' ') + 'Yes ' +
('>' if self.confirm == 0 else ' ') + 'No ' +
('>' if self.confirm == 2 else ' ') + 'Quit')
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/radio.py | examples/plugins/radio.py | import atexit
import re
import socket
import subprocess
import time
from sys import version_info
from dot3k.menu import MenuOption
class Radio(MenuOption):
def __init__(self):
MenuOption.__init__(self)
self.ready = False
self.stations = None
self.selected_station = 0
self.selected_option = 0
self.pid = None
self.socket = None
self.current_stream = None
self.current_state = None
# Keep track of whether we've started a VLC instance
self.started_vlc_instance = False
self.last_update = 0
self.mode = 'main'
atexit.register(self.kill)
self.icons = {
'play': [0, 24, 30, 31, 30, 24, 0, 0],
'pause': [0, 27, 27, 27, 27, 27, 0, 0],
'stop': [0, 31, 31, 31, 31, 31, 0, 0]
}
def setup(self, config):
self.ready = False
MenuOption.setup(self, config)
if 'Radio Stations' in self.config.sections():
self.stations = self.config.options('Radio Stations')
self.ready = True
self.start()
def prev_station(self):
station = self.selected_station - 1
if station < 0:
station = len(self.stations) - 1
return station
def next_station(self):
station = self.selected_station + 1
if station >= len(self.stations):
station = 0
return station
def next_option(self):
self.selected_option += 1
self.selected_option %= 3
def prev_option(self):
self.selected_option -= 1
self.selected_option %= 3
def down(self):
if self.mode == 'main':
self.next_option()
else:
self.selected_station = self.next_station()
def up(self):
if self.mode == 'main':
self.prev_option()
else:
self.selected_station = self.prev_station()
def right(self):
if self.mode == 'main':
if self.selected_option == 0:
self.mode = 'list'
elif self.selected_option == 1:
self.send('pause')
elif self.selected_option == 2 and self.current_state == 'playing':
self.send('stop')
elif self.selected_option == 2 and self.current_state == 'stopped':
self.send('play')
else:
self.play_selected_station()
def left(self):
if self.mode == 'main':
return False
else:
self.mode = 'main'
return True
def play_selected_station(self):
stream = self.config.get(
'Radio Stations',
self.stations[self.selected_station]
)
if ',' in stream:
stream = stream.split(',')[1]
if stream == self.get_current_stream():
print('Skipping play, sending play/pause toggle')
self.send("pause")
return False
self.send("add " + stream)
def redraw(self, menu):
if self.millis() - self.last_update > 500:
self.get_current_stream()
self.last_update = self.millis()
if self.mode == 'list':
self.redraw_stations(menu)
elif self.mode == 'main':
self.redraw_main(menu)
def redraw_main(self, menu):
# Row, Text, Icon, Left Margin
menu.write_option(0, 'Stations', chr(252) if self.selected_option == 0 else ' ', 1)
menu.write_option(1, 'Pause' if self.current_state != 'paused' else 'Resume',
chr(252) if self.selected_option == 1 else ' ', 1)
menu.write_option(2, 'Stop' if self.current_state != 'stopped' else 'Play',
chr(252) if self.selected_option == 2 else ' ', 1)
def redraw_stations(self, menu):
if not self.ready:
menu.clear_row(0)
menu.write_row(1, 'No stations found!')
menu.clear_row(2)
return False
if len(self.stations) > 2:
self.draw_station(menu, 0, self.prev_station())
self.draw_station(menu, 1, self.selected_station)
if len(self.stations) > 1:
self.draw_station(menu, 2, self.next_station())
def draw_station(self, menu, row, index):
stream = self.config.get('Radio Stations', self.stations[index])
title = stream.split(',')[0]
stream = stream.split(',')[1]
icon = ' '
if self.selected_station == index:
icon = chr(252)
if stream == self.current_stream:
if self.current_state == 'paused':
menu.lcd.create_char(0, self.icons['pause'])
icon = chr(0)
elif self.current_state == 'playing':
menu.lcd.create_char(0, self.icons['play'])
icon = chr(0)
else:
menu.lcd.create_char(0, self.icons['stop'])
icon = chr(0)
menu.write_option(row, title, icon)
def kill(self):
if self.pid is not None and self.started_vlc_instance:
subprocess.call(['/bin/kill', '-9', str(self.pid)])
print('Killing VLC process with PID: ' + str(self.pid))
def send(self, command):
try:
if version_info[0] >= 3:
self.socket.send((command + "\n").encode('utf-8'))
else:
self.socket.send(command + "\n")
except socket.error:
print('Failed to send command to VLC')
def get_current_stream(self):
self.send("status")
status = self.socket.recv(8192)
if version_info[0] >= 3:
status = status.decode('utf-8')
result = re.search('input:\ (.*)\ ', status)
state = re.search('state\ (.*)\ ', status)
if state is not None:
self.current_state = state.group(1)
if result is not None:
self.current_stream = result.group(1)
else:
self.current_stream = None
return self.current_stream
def connect(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for attempt in range(10):
try:
print("Attempting to connect to VLC")
self.socket.connect(("127.0.0.1", 9393))
print("Connection successful!")
return True
except socket.error:
time.sleep(1)
try:
self.socket.recv(0)
except socket.error:
return False
def start(self):
if self.pid is None:
try:
return_value = subprocess.check_output(['pidof', 'vlc'])
if version_info[0] >= 3:
self.pid = int(return_value.decode('utf-8').split(' ')[0])
else:
self.pid = int(return_value.decode('utf-8').split(' ')[0])
print('Found VLC with PID: ' + str(self.pid))
if self.connect():
return True
except subprocess.CalledProcessError:
pass
try:
return_value = subprocess.check_output(['./vlc.sh'])
pids = return_value.decode('utf-8').split('\n')[0]
self.pid = int(pids.split(' ')[0])
self.started_vlc_instance = True
print('VLC started with PID: ' + str(self.pid))
except subprocess.CalledProcessError:
print('You must have VLC installed to use Dot3k Radio')
print('Try: sudo apt-get install vlc')
exit()
if not self.connect():
exit("Unable to connect to VLC")
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/writing_your_own/03_doing_stuff.py | examples/plugins/writing_your_own/03_doing_stuff.py | #!/usr/bin/env python
"""
Building upon our options example, we'll now explore running
scynronous ( short ) and asyncronous/background ( long ) tasks
in response to both menu options being selected and on a schedule.
There are many ways that tasks can be run, in a thread, every n seconds,
or in direct response to a menu option being selected.
A task can be as simple as switching to a different menu mode, and changing
what's on the display... or as complex as calling a system process
and updating some stored information for display.
The code in this example is a decent way to handle options and actions,
but it's far from the only way.
"""
import subprocess
import threading
from dot3k.menu import MenuOption
class HelloWorld(MenuOption):
"""
If you're not sure what's going on here, see 02_handling_options.py
"""
def __init__(self):
self.selected_option = 0
self.options = [
'Pirate',
'Monkey',
'Robot',
'Ninja',
'Dolphin'
]
"""
Python has no "switch" so we'll store an array of functions
to call when an option is selected
"""
self.actions = [
self.handle_pirate,
self.handle_monkey,
self.handle_robot,
self.handle_ninja,
self.handle_dolphin,
]
MenuOption.__init__(self)
"""
Here we'll define the things each menu option will do.
Our up/down/left/right and select methods are *never* passed
a reference to menu, and it's deliberately difficult to draw
anything to the screen in direct response to a button click.
This is because the screen will either be instantly redrawn
by the "redraw" method, or you'll have to hang the whole
user-interface with time.sleep, icky!
Instead, we should hand anything complex to a thread or change a state-machine
and act accordingly on the next redraw.
"""
"""
When the pirate option is selected, we want to update something
in the background. We can use a thread for that.
We'll update the pirate icon to indicate that it's busy
and so we know something is happening.
"""
def handle_pirate(self):
print('Arrr! Doing pirate stuff!')
update = threading.Thread(None, self.do_pirate_update)
update.daemon = True
update.start()
"""
This is the method we call in our thread.
After we're done pinging google, print out the last line of the result
and clear the icon.
"""
def do_pirate_update(self):
result = subprocess.check_output(['/bin/ping', 'google.com', '-c', '4'])
result = result.split("\n")
result = result[len(result) - 2]
print(result)
def handle_monkey(self):
print('Eeek! Doing monkey stuff!')
time.sleep(2)
print('Done monkey stuff!')
def handle_robot(self):
print('Deep! Doing robot stuff!')
def handle_ninja(self):
print('Hyah! Doing Ninja stuff!')
def handle_dolphin(self):
print('Bubble bubble bubble!')
"""
To run an option we can simply call its associated function.
"""
def select_option(self):
self.actions[self.selected_option]()
"""
UP/DOWN are handy directions for selecting the previous and next
option in a list. So we create functions to increment/decriment
the selected_option. Using modulus ( % ) is an easy way to wrap them
when we reach 0 or the length of the options array above.
"""
def next_option(self):
self.selected_option = (self.selected_option + 1) % len(self.options)
def prev_option(self):
self.selected_option = (self.selected_option - 1) % len(self.options)
def up(self):
self.prev_option()
def down(self):
self.next_option()
"""
The "right" direction is much easier to press than select,
so I tend to use it as the "action" button for selecting options
"""
def right(self):
self.select_option()
def get_current_option(self):
return self.options[self.selected_option]
def get_next_option(self):
return self.options[(self.selected_option + 1) % len(self.options)]
def get_prev_option(self):
return self.options[(self.selected_option - 1) % len(self.options)]
def redraw(self, menu):
menu.write_option(
row=0,
margin=1,
icon='',
text=self.get_prev_option()
)
menu.write_option(
row=1,
margin=1,
icon='>', # Let's use a > to denote the currently selected option
text=self.get_current_option()
)
menu.write_option(
row=2,
margin=1,
icon='',
text=self.get_next_option()
)
from dot3k.menu import Menu
import dot3k.joystick
import dot3k.backlight
import dot3k.lcd
import time
dot3k.backlight.rgb(255, 255, 255)
menu = Menu(
structure={
'Hello World': HelloWorld()
},
lcd=dot3k.lcd
)
"""
We'll virtually press "right" to
enter your plugin:
"""
menu.right()
"""
We need to handle UP/DOWN to select the
previous/next option.
"""
@dot3k.joystick.on(dot3k.joystick.UP)
def handle_up(pin):
menu.up()
@dot3k.joystick.on(dot3k.joystick.DOWN)
def handle_down(pin):
menu.down()
"""
We need to handle right, to let us choose the selected option
"""
@dot3k.joystick.on(dot3k.joystick.RIGHT)
def handle_right(pin):
menu.right()
"""
You can decide when the menu is redrawn, but
you'll usually want to do this:
"""
while 1:
menu.redraw()
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/writing_your_own/02_handling_options.py | examples/plugins/writing_your_own/02_handling_options.py | #!/usr/bin/env python
"""
This example builds upon our hello_world plugin,
now we're going to add some options to cycle though.
Because interfaces can differ widely, there are no helpers
for displaying and cycling through options. You might choose
to lay out icons on a single screen/row or cycle through
multiple lines of text.
In this example, we're going to to the latter!
"""
from dot3k.menu import MenuOption
class HelloWorld(MenuOption):
"""
First we introduce __init__, this is called when your plugin
is first instantiated and is where you should create the variables
you wish to use.
You *must* also call MenuOption.__init__(self)
"""
def __init__(self):
"""
We need somewhere to track which option is selected
"""
self.selected_option = 0
"""
We should also keep track of what the options are
"""
self.options = [
'Pirate',
'Monkey',
'Robot',
'Ninja',
'Dolphin'
]
"""
You *must* call the __init__ method on the parent class
"""
MenuOption.__init__(self)
"""
These functions let us move between options,
wrapping around when we reach the lowest or highest
The use of modulus ( % ) is an easy way to wrap around
without any pesky, complex logic
"""
def next_option(self):
self.selected_option = (self.selected_option + 1) % len(self.options)
def prev_option(self):
self.selected_option = (self.selected_option - 1) % len(self.options)
"""
We'll need to override the up/down control methods
to call our next/prev methods
"""
def up(self):
self.prev_option()
def down(self):
self.next_option()
"""
And these are some handy functions for getting the prev/next/current
option text for display on the menu.
"""
def get_current_option(self):
return self.options[self.selected_option]
def get_next_option(self):
return self.options[(self.selected_option + 1) % len(self.options)]
def get_prev_option(self):
return self.options[(self.selected_option - 1) % len(self.options)]
"""
When the menu is redrawn, it calls your plugins
redraw method and passes an instance of itself.
"""
def redraw(self, menu):
menu.write_option(
row=0,
margin=1,
text=self.get_prev_option()
)
menu.write_option(
row=1,
margin=1,
icon='>',
text=self.get_current_option()
)
menu.write_option(
row=2,
margin=1,
text=self.get_next_option()
)
from dot3k.menu import Menu
import dot3k.joystick
import dot3k.backlight
import dot3k.lcd
import time
"""
Let there be light!
"""
dot3k.backlight.rgb(255, 255, 255)
"""
The menu structure is defined as a nested dictionary,
to "install" your plugin, it should be added like so:
You will also need to pass Menu a reference to the LCD
you wish to draw to.
"""
menu = Menu(
structure={
'Hello World': HelloWorld()
},
lcd=dot3k.lcd
)
"""
We'll virtually press "right" to
enter your plugin:
"""
menu.right()
"""
We will also need to handle up/down
to let us select options
"""
@dot3k.joystick.on(dot3k.joystick.UP)
def handle_up(pin):
menu.up()
@dot3k.joystick.on(dot3k.joystick.DOWN)
def handle_down(pin):
menu.down()
"""
You can decide when the menu is redrawn, but
you'll usually want to do this:
"""
while 1:
menu.redraw()
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/writing_your_own/04_adding_icons.py | examples/plugins/writing_your_own/04_adding_icons.py | #!/usr/bin/env python
"""
Building upon our doing stuff example, we'll now add icons to show
when things are running.
"""
import subprocess
import threading
from dot3k.menu import MenuOption
class HelloWorld(MenuOption):
"""
If you're not sure what's going on here, see 02_handling_options.py
"""
def __init__(self):
self.selected_option = 0
"""
Python has no "switch" so we'll store an array of functions
to call when an option is selected.
We've added icons to this example, so instead of two arrays
we've collected all the related stuff into an array of
dictionaries.
"""
self.options = [
{'title': 'Pirate', 'action': self.handle_pirate, 'icon': ' '}
{'title': 'Pirate', 'action': self.handle_monkey, 'icon': ' '}
{'title': 'Pirate', 'action': self.handle_robot, 'icon': ' '}
{'title': 'Pirate', 'action': self.handle_ninja, 'icon': ' '}
{'title': 'Pirate', 'action': self.handle_dolphin, 'icon': ' '}
]
MenuOption.__init__(self)
"""
Here we'll define the things each menu option will do.
Our up/down/left/right and select methods are *never* passed
a reference to menu, and it's deliberately difficult to draw
anything to the screen in direct response to a button click.
This is because the screen will either be instantly redrawn
by the "redraw" method, or you'll have to hang the whole
user-interface with time.sleep, icky!
Instead, we should hand anything complex to a thread or state change.
"""
"""
When the pirate option is selected, we want to update something
in the background. We can use a thread for that.
We'll update the pirate icon to indicate that it's busy
and so we know something is happening.
"""
def handle_pirate(self):
print('Arrr! Doing pirate stuff!')
self.icons[0] = '!'
update = threading.Thread(None, self.do_pirate_update)
update.daemon = True
update.start()
"""
This is the method we call in our thread.
After we're done pinging google, print out the last line of the result
and clear the icon.
"""
def do_pirate_update(self):
result = subprocess.check_output(['/bin/ping','google.com','-c','4'])
result = result.split("\n")
result = result[len(result)-2]
print(result)
self.icons[0] = ' '
def handle_monkey(self):
print('Eeek! Doing monkey stuff!')
self.icons[1] = '!'
time.sleep(2)
self.icons[1] = ' '
def handle_robot(self):
print('Deep! Doing robot stuff!')
def handle_ninja(self):
print('Hyah! Doing Ninja stuff!')
def handle_dolphin(self):
print('Bubble bubble bubble!')
"""
To run an option we can simply call its associated function.
This can be done by adding brackets to the action.
"""
def select_option(self):
self.actions[ self.selected_option ]['action']()
def next_option(self):
self.selected_option = (self.selected_option + 1) % len(self.options)
def prev_option(self):
self.selected_option = (self.selected_option - 1) % len(self.options)
def up(self):
self.prev_option()
def down(self):
self.next_option()
"""
The "right" direction is much easier to press than select,
so I tend to use it as the "action" button for selecting options
"""
def right(self):
self.select_option()
def get_current_option(self):
return self.options[ self.selected_option ]['title']
def get_next_option(self):
return self.options[ (self.selected_option + 1) % len(self.options) ]['title']
def get_prev_option(self):
return self.options[ (self.selected_option - 1) % len(self.options) ]['title']
"""
A few helpers for getting the icons couldn't hurt either!
"""
def get_current_icon(self):
return self.options[ self.selected_option ]['icon']
def get_next_icon(self):
return self.options[ (self.selected_option + 1) % len(self.options) ]['icon']
def get_prev_icon(self):
return self.options[ (self.selected_option - 1) % len(self.options) ]['icon']
def redraw(self, menu):
menu.write_option(
row=0,
margin=1,
icon=self.get_prev_icon(),
text=self.get_prev_option()
)
menu.write_option(
row=1,
margin=1,
icon=self.get_current_icon() or '>',
text=self.get_current_option()
)
menu.write_option(
row=2,
margin=1,
icon=self.get_next_icon(),
text=self.get_next_option()
)
from dot3k.menu import Menu
import dot3k.joystick
import dot3k.backlight
import dot3k.lcd
import time
dot3k.backlight.rgb(255,255,255)
menu = Menu(
structure={
'Hello World':HelloWorld()
},
lcd=dot3k.lcd
)
"""
We'll virtually press "right" to
enter your plugin:
"""
menu.right()
@dot3k.joystick.on(dot3k.joystick.UP)
def handle_up(pin):
menu.up()
@dot3k.joystick.on(dot3k.joystick.DOWN)
def handle_down(pin):
menu.down()
"""
We need to handle right, to let us select options
"""
@dot3k.joystick.on(dot3k.joystick.RIGHT)
def handle_right(pin):
menu.right()
"""
You can decide when the menu is redrawn, but
you'll usually want to do this:
"""
while 1:
menu.redraw()
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/examples/plugins/writing_your_own/01_hello_world.py | examples/plugins/writing_your_own/01_hello_world.py | #!/usr/bin/env python
"""
Every dot3k.menu plugin is derived from MenuOption
"""
from dot3k.menu import MenuOption
class HelloWorld(MenuOption):
"""
When the menu is redrawn, it calls your plugins
redraw method and passes an instance of itself.
"""
def redraw(self, menu):
"""
The instance of menu has a couple of useful
methods which you can use to draw to the screen
menu.write_row(row_number, text_string) will write
a simple string to the screen at the row you choose.
It's a fast, no-frills way of drawing.
Anything longer than 16 characters will get truncated!
"""
menu.write_row(0, 'Hello World Hello?')
"""
menu.write_option() is a lot more complex, it lets
you position text with icons, margins and auto-scrolling.
Let's give it a go with a long string of text!
"""
menu.write_option(
row=1,
text='Hello World! How are you today?',
scroll=True
)
"""
If you're not going to use a row, you should clear it!
"""
menu.clear_row(2)
from dot3k.menu import Menu
import dot3k.backlight
import dot3k.lcd
import time
"""
Let there be light!
"""
dot3k.backlight.rgb(255, 255, 255)
"""
The menu structure is defined as a nested dictionary,
to "install" your plugin, it should be added like so:
You will also need to pass Menu a reference to the LCD
you wish to draw to.
"""
menu = Menu(
structure={
'Hello World': HelloWorld()
},
lcd=dot3k.lcd
)
"""
We're not going to handle any input, so go
right ahead and virtually press "right" to
enter your plugin:
"""
menu.right()
"""
You can decide when the menu is redrawn, but
you'll usually want to do this:
"""
while 1:
menu.redraw()
time.sleep(0.01)
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
pimoroni/displayotron | https://github.com/pimoroni/displayotron/blob/1161818428c393906fdf437c8fa51f51b329af1e/sphinx/conf.py | sphinx/conf.py | #-*- coding: utf-8 -*-
import sys
import site
from unittest import mock
# Prompte /usr/local/lib to the front of sys.path
#sys.path.insert(0,site.getsitepackages()[0])
import sphinx_rtd_theme
sys.modules['cap1xxx'] = mock.Mock()
sys.modules['st7036'] = mock.Mock()
sys.modules['sn3218'] = mock.Mock()
sys.modules['RPi'] = mock.Mock()
sys.modules['RPi.GPIO'] = mock.Mock()
sys.modules['sn3218'].default_gamma_table = []
sys.path.insert(0, '../library/')
from sphinx.ext import autodoc
class OutlineMethodDocumenter(autodoc.MethodDocumenter):
objtype = 'method'
def add_content(self, more_content, no_docstring=False):
return
class OutlineFunctionDocumenter(autodoc.FunctionDocumenter):
objtype = 'function'
def add_content(self, more_content, no_docstring=False):
return
class ModuleOutlineDocumenter(autodoc.ModuleDocumenter):
objtype = 'moduleoutline'
def __init__(self, directive, name, indent=u''):
# Monkey path the Method and Function documenters
sphinx_app.add_autodocumenter(OutlineMethodDocumenter)
sphinx_app.add_autodocumenter(OutlineFunctionDocumenter)
autodoc.ModuleDocumenter.__init__(self, directive, name, indent)
def __del__(self):
# Return the Method and Function documenters to normal
sphinx_app.add_autodocumenter(autodoc.MethodDocumenter)
sphinx_app.add_autodocumenter(autodoc.FunctionDocumenter)
def setup(app):
global sphinx_app
sphinx_app = app
app.add_autodocumenter(ModuleOutlineDocumenter)
ModuleOutlineDocumenter.objtype = 'module'
import dot3k
import dothat
PACKAGE_NAME = u"Display-o-Tron"
PACKAGE_HANDLE = "displayotron"
PACKAGE_MODULE = "displayotron"
PACKAGE_VERSION = dothat.__version__
suppress_warnings = ["app.add_directive"]
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = PACKAGE_NAME
copyright = u'2017, Pimoroni Ltd'
author = u'Phil Howard'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'{}'.format(PACKAGE_VERSION)
# The full version, including alpha/beta/rc tags.
release = u'{}'.format(PACKAGE_VERSION)
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
#html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'collapse_navigation': False,
'display_version': True
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [
'_themes',
sphinx_rtd_theme.get_html_theme_path()
]
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = PACKAGE_NAME + u' v0.1.2'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
html_logo = 'shop-logo.png'
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = 'favicon.png'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
html_use_index = False
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = PACKAGE_HANDLE + 'doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, PACKAGE_HANDLE + '.tex', PACKAGE_NAME + u' Documentation',
u'Phil Howard', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# It false, will not define \strong, \code, itleref, \crossref ... but only
# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
# packages.
#
# latex_keep_old_macro_names = True
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, PACKAGE_MODULE, PACKAGE_NAME + u' Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, PACKAGE_HANDLE, PACKAGE_NAME + u' Documentation',
author, PACKAGE_HANDLE, 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
| python | MIT | 1161818428c393906fdf437c8fa51f51b329af1e | 2026-01-05T07:12:43.667300Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/setup.py | bloodhound_search/setup.py | #!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
from setuptools import setup
DESC = """Search plugin for Apache(TM) Bloodhound.
Add free text search and query functionality to Bloodhound sites.
"""
versions = [
(0, 4, 0),
(0, 5, 0),
(0, 6, 0),
(0, 7, 0),
(0, 8, 0),
(0, 9, 0),
]
latest = '.'.join(str(x) for x in versions[-1])
status = {
'planning': "Development Status :: 1 - Planning",
'pre-alpha': "Development Status :: 2 - Pre-Alpha",
'alpha': "Development Status :: 3 - Alpha",
'beta': "Development Status :: 4 - Beta",
'stable': "Development Status :: 5 - Production/Stable",
'mature': "Development Status :: 6 - Mature",
'inactive': "Development Status :: 7 - Inactive"
}
dev_status = status["alpha"]
cats = [
dev_status,
"Environment :: Plugins",
"Environment :: Web Environment",
"Framework :: Trac",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: Other Audience",
"Intended Audience :: System Administrators",
"License :: Unknown",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Software Development :: Bug Tracking",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
]
# Add the change log to the package description.
chglog = None
try:
from os.path import dirname, join
chglog = open(join(dirname(__file__), "CHANGES"))
DESC += ('\n\n' + chglog.read())
finally:
if chglog:
chglog.close()
DIST_NM = 'BloodhoundSearchPlugin'
PKG_INFO = {'bhsearch': ('bhsearch', # Package dir
# Package data
['../CHANGES', '../TODO', '../COPYRIGHT',
'../NOTICE', '../README', '../TESTING_README',
'htdocs/*.*', 'htdocs/css/*.css',
'htdocs/img/*.*', 'htdocs/js/*.js',
'templates/*', 'default-pages/*',
'locale/*/LC_MESSAGES/*.mo'],
),
'bhsearch.search_resources': (
'bhsearch/search_resources', # Package dir
[]
),
# 'search.widgets' : ('bhsearch/widgets', # Package dir
# # Package data
# ['templates/*', 'htdocs/*.css'],
# ),
# 'search.layouts' : ('bhsearch/layouts', # Package dir
# # Package data
# ['templates/*'],
# ),
'bhsearch.tests': ('bhsearch/tests', # Package dir
# Package data
['data/*.*'],
),
'bhsearch.tests.search_resources': (
'bhsearch/tests/search_resources', # Package dir
# Package data
['data/*.*'],
),
'bhsearch.utils': ('bhsearch/utils', # Package dir
# Package data
[],
),
}
ENTRY_POINTS = {
'trac.plugins': [
'bhsearch.web_ui = bhsearch.web_ui',
'bhsearch.api = bhsearch.api',
'bhsearch.admin = bhsearch.admin',
'bhsearch.search_resources.changeset_search =\
bhsearch.search_resources.changeset_search',
'bhsearch.search_resources.ticket_search =\
bhsearch.search_resources.ticket_search',
'bhsearch.search_resources.wiki_search = \
bhsearch.search_resources.wiki_search',
'bhsearch.search_resources.milestone_search = \
bhsearch.search_resources.milestone_search',
'bhsearch.query_parser = bhsearch.query_parser',
'bhsearch.query_suggestion = bhsearch.query_suggestion',
'bhsearch.security = bhsearch.security',
'bhsearch.whoosh_backend = bhsearch.whoosh_backend',
],
}
extra = {}
try:
from trac.util.dist import get_l10n_cmdclass
cmdclass = get_l10n_cmdclass()
if cmdclass:
extra['cmdclass'] = cmdclass
extractors = [
('**.py', 'trac.dist:extract_python', None),
('**/templates/**.html', 'genshi', None),
('**/templates/**.txt', 'genshi', {
'template_class': 'genshi.template:TextTemplate'
}),
]
extra['message_extractors'] = {
'bhsearch': extractors,
}
except ImportError:
pass
setup(
name=DIST_NM,
version=latest,
description=DESC.split('\n', 1)[0],
author="Apache Bloodhound",
license="Apache License v2",
url="https://bloodhound.apache.org/",
requires=['trac'],
install_requires=['whoosh>=2.5.1'],
package_dir=dict([p, i[0]] for p, i in PKG_INFO.iteritems()),
packages=PKG_INFO.keys(),
package_data=dict([p, i[1]] for p, i in PKG_INFO.iteritems()),
include_package_data=True,
provides=['%s (%s)' % (p, latest) for p in PKG_INFO.keys()],
obsoletes=['%s (>=%s.0.0, <%s)' % (p, versions[-1][0], latest) \
for p in PKG_INFO.keys()],
entry_points=ENTRY_POINTS,
classifiers=cats,
long_description=DESC,
test_suite='bhsearch.tests.test_suite',
tests_require=['unittest2'] if sys.version_info < (2, 7) else [],
**extra
)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/api.py | bloodhound_search/bhsearch/api.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Core Bloodhound Search components."""
from trac.config import ExtensionOption, OrderedExtensionsOption
from trac.core import (Interface, Component, ExtensionPoint, TracError,
implements)
from trac.env import IEnvironmentSetupParticipant
from multiproduct.api import ISupportMultiProductEnvironment
from multiproduct.core import MultiProductExtensionPoint
from bhsearch.utils.translation import _, add_domain
ASC = "asc"
DESC = "desc"
SCORE = "score"
class IndexFields(object):
TYPE = "type"
ID = "id"
TIME = 'time'
AUTHOR = 'author'
CONTENT = 'content'
STATUS = 'status'
PRODUCT = 'product'
REQUIRED_PERMISSION = 'required_permission'
NAME = 'name'
class QueryResult(object):
def __init__(self):
self.hits = 0
self.page_count = 0
self.page_number = 0
self.offset = 0
self.docs = []
self.highlighting = []
self.facets = None
self.query_suggestion = None
self.debug = {}
class SortInstruction(object):
def __init__(self, field, order):
self.field = field
self.order = self._parse_sort_order(order)
def _parse_sort_order(self, order):
if not order:
return ASC
order = order.strip().lower()
if order == ASC:
return ASC
elif order == DESC:
return DESC
else:
raise TracError(
"Invalid sort order %s in sort instruction" % order)
def build_sort_expression(self):
return "%s %s" % (self.field, self.order)
def __str__(self):
return str(self.__dict__)
def __eq__(self, other):
if not isinstance(other, SortInstruction):
return False
return self.__dict__ == other.__dict__
class ISearchWikiSyntaxFormatter(Interface):
"""Extension point interface for wiki syntax processing.
"""
def format(self, wiki_text):
"""
Process wiki syntax and return text representation suitable for search
"""
class ISearchBackend(Interface):
"""Extension point interface for search backend systems.
"""
def add_doc(doc, operation_context):
"""
Called when new document instance must be added
"""
def delete_doc(product, doc_type, doc_id, operation_context):
"""
Delete document from index
"""
def optimize():
"""
Optimize index if needed
"""
def is_index_outdated():
"""
Check if index is outdated and needs to be recreated.
"""
def recreate_index():
"""
Create a new index, if index exists, it will be deleted
"""
def open_or_create_index_if_missing():
"""
Open existing index, if index does not exist, create new one
"""
def query(
query,
sort = None,
fields = None,
filter = None,
facets = None,
pagenum = 1,
pagelen = 20,
highlight=False,
highlight_fields=None,
context=None):
"""
Perform query implementation
:param query: Parsed query object
:param sort: list of SortInstruction objects
:param fields: list of fields to select
:param boost: list of fields with boost values
:param filter: filter query object
:param facets: list of facet fields
:param pagenum: page number
:param pagelen: page length
:param highlight: highlight matched terms in fields
:param highlight_fields: list of fields to highlight
:return: ResultsPage
"""
def start_operation(self):
"""Used to get arguments for batch operation withing single commit"""
class IIndexParticipant(Interface):
"""Extension point interface for components that should be searched.
"""
def get_entries_for_index():
"""List entities for index creation"""
class ISearchParticipant(Interface):
"""Extension point interface for components that should be searched.
"""
def format_search_results(contents):
"""Called to see if the module wants to format the search results."""
def is_allowed(req):
"""Called when we want to build the list of components with search.
Passes the request object to do permission checking."""
def get_participant_type():
"""Return type of search participant"""
def get_required_permission(self):
"""Return permission required to view components in search results"""
def get_title():
"""Return resource title."""
def get_default_facets():
"""Return default facets for the specific resource type."""
def get_default_view():
"""Return True if grid is enabled by default for specific resource."""
def get_default_view_fields(view):
"""Return list of fields should be returned in grid by default."""
class IQueryParser(Interface):
"""Extension point for Bloodhound Search query parser.
"""
def parse(query_string, context):
"""Parse query from string"""
def parse_filters(filters):
"""Parse query filters"""
class IDocIndexPreprocessor(Interface):
"""Extension point for Bloodhound Search document pre-processing before
adding or update documents into index.
"""
def pre_process(doc):
"""Process document"""
class IResultPostprocessor(Interface):
"""Extension point for Bloodhound Search result post-processing before
returning result to caller.
"""
def post_process(query_result):
"""Process document"""
class IQueryPreprocessor(Interface):
"""Extension point for Bloodhound Search query pre processing.
"""
def query_pre_process(query_parameters, context):
"""Process query parameters"""
class IMetaKeywordParser(Interface):
"""Extension point for custom meta keywords."""
def match(text, context):
"""If text matches the keyword, return its transformed value."""
class BloodhoundSearchApi(Component):
"""Implements core indexing functionality, provides methods for
searching, adding and deleting documents from index.
"""
implements(IEnvironmentSetupParticipant, ISupportMultiProductEnvironment)
def __init__(self, *args, **kwargs):
import pkg_resources
locale_dir = pkg_resources.resource_filename(__name__, 'locale')
add_domain(self.env.path, locale_dir)
super(BloodhoundSearchApi, self).__init__(*args, **kwargs)
backend = ExtensionOption('bhsearch', 'search_backend',
ISearchBackend, 'WhooshBackend',
'Name of the component implementing Bloodhound Search backend \
interface: ISearchBackend.', doc_domain='bhsearch')
parser = ExtensionOption('bhsearch', 'query_parser',
IQueryParser, 'DefaultQueryParser',
'Name of the component implementing Bloodhound Search query \
parser.', doc_domain='bhsearch')
index_pre_processors = OrderedExtensionsOption(
'bhsearch', 'index_preprocessors', IDocIndexPreprocessor,
['SecurityPreprocessor'], include_missing=True,
)
result_post_processors = ExtensionPoint(IResultPostprocessor)
query_processors = ExtensionPoint(IQueryPreprocessor)
index_participants = MultiProductExtensionPoint(IIndexParticipant)
def query(
self,
query,
sort = None,
fields = None,
filter = None,
facets = None,
pagenum = 1,
pagelen = 20,
highlight = False,
highlight_fields = None,
context = None):
"""Return query result from an underlying search backend.
Arguments:
:param query: query string e.g. “bla status:closed” or a parsed
representation of the query.
:param sort: optional sorting
:param boost: optional list of fields with boost values e.g.
{“id”: 1000, “subject” :100, “description”:10}.
:param filter: optional list of terms. Usually can be cached by
underlying search framework. For example {“type”: “wiki”}
:param facets: optional list of facet terms, can be field or expression
:param page: paging support
:param pagelen: paging support
:param highlight: highlight matched terms in fields
:param highlight_fields: list of fields to highlight
:param context: request context
:return: result QueryResult
"""
# pylint: disable=too-many-locals
self.env.log.debug("Receive query request: %s", locals())
parsed_query = self.parser.parse(query, context)
parsed_filters = self.parser.parse_filters(filter)
# TODO: add query parsers and meta keywords post-parsing
# TODO: apply security filters
query_parameters = dict(
query = parsed_query,
query_string = query,
sort = sort,
fields = fields,
filter = parsed_filters,
facets = facets,
pagenum = pagenum,
pagelen = pagelen,
highlight = highlight,
highlight_fields = highlight_fields,
)
for query_processor in self.query_processors:
query_processor.query_pre_process(query_parameters, context)
query_result = self.backend.query(**query_parameters)
for post_processor in self.result_post_processors:
post_processor.post_process(query_result)
query_result.debug["api_parameters"] = query_parameters
return query_result
def start_operation(self):
return self.backend.start_operation()
def rebuild_index(self):
"""Rebuild underlying index"""
self.log.info('Rebuilding the search index.')
self.backend.recreate_index()
with self.backend.start_operation() as operation_context:
doc = None
try:
for participant in self.index_participants:
self.log.info(
"Reindexing resources provided by %s in product %s" %
(participant.__class__.__name__,
getattr(participant.env.product, 'name', "''"))
)
docs = participant.get_entries_for_index()
for doc in docs:
self.log.debug(
"Indexing document %s:%s/%s" % (
doc.get('product'),
doc['type'],
doc['id'],
)
)
self.add_doc(doc, operation_context)
self.log.info("Reindexing complete.")
except Exception, ex:
self.log.error(ex)
if doc:
self.log.error("Doc that triggers the error: %s" % doc)
raise
def change_doc_id(self, doc, old_id, operation_context=None):
if operation_context is None:
with self.backend.start_operation() as operation_context:
self._change_doc_id(doc, old_id, operation_context)
else:
self._change_doc_id(doc, old_id, operation_context)
def _change_doc_id(self, doc, old_id, operation_context):
self.backend.delete_doc(
doc[IndexFields.PRODUCT],
doc[IndexFields.TYPE],
old_id,
operation_context
)
self.add_doc(doc, operation_context)
def optimize(self):
"""Optimize underlying index"""
self.backend.optimize()
def add_doc(self, doc, operation_context = None):
"""Add a document to underlying search backend.
The doc must be dictionary with obligatory "type" field
"""
for preprocessor in self.index_pre_processors:
preprocessor.pre_process(doc)
self.backend.add_doc(doc, operation_context)
def delete_doc(self, product, doc_type, doc_id):
"""Delete the document from underlying search backend.
"""
self.backend.delete_doc(product, doc_type, doc_id)
# IEnvironmentSetupParticipant methods
def environment_created(self):
self.upgrade_environment(self.env.db_transaction)
def environment_needs_upgrade(self, db):
# pylint: disable=unused-argument
return self.backend.is_index_outdated()
def upgrade_environment(self, db):
# pylint: disable=unused-argument
self.rebuild_index()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/security.py | bloodhound_search/bhsearch/security.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from itertools import groupby
import os
from trac.core import Component, implements, ExtensionPoint
from trac.perm import PermissionSystem
from tracopt.perm.authz_policy import AuthzPolicy
from whoosh import query
from multiproduct.env import ProductEnvironment
from bhsearch.api import (IDocIndexPreprocessor, IndexFields,
IQueryPreprocessor, ISearchParticipant)
from bhsearch.utils import get_product, instance_for_every_env, is_enabled
class SecurityPreprocessor(Component):
participants = ExtensionPoint(ISearchParticipant)
def __init__(self):
self._required_permissions = {}
for participant in self.participants:
permission = participant.get_required_permission()
doc_type = participant.get_participant_type()
self._required_permissions[doc_type] = permission
def check_permission(self, doc, context):
product, doctype, id = doc.get('product'), doc['type'], doc['id']
username = context.req.authname
env = self.env
if product:
env = ProductEnvironment(self.env, product)
perm = PermissionSystem(env)
action = self._required_permissions[doctype]
return perm.check_permission(action, username, id)
def update_security_filter(self, query_parameters, allowed=(), denied=()):
security_filter = self.create_security_filter(query_parameters)
security_filter.add_allowed(allowed)
security_filter.add_denied(denied)
def create_security_filter(self, query_parameters):
security_filter = self.find_security_filter(query_parameters['filter'])
if not security_filter:
security_filter = SecurityFilter()
if query_parameters['filter']:
query_parameters['filter'] = query.And([query_parameters['filter'],
security_filter])
else:
query_parameters['filter'] = security_filter
return security_filter
def find_security_filter(self, existing_query):
queue = [existing_query]
while queue:
token = queue.pop(0)
if isinstance(token, SecurityFilter):
return token
if isinstance(token, query.CompoundQuery):
queue.extend(token.subqueries)
class DefaultSecurityPreprocessor(SecurityPreprocessor):
implements(IDocIndexPreprocessor, IQueryPreprocessor)
# IDocIndexPreprocessor methods
def pre_process(self, doc):
permission = self._required_permissions[doc[IndexFields.TYPE]]
doc[IndexFields.REQUIRED_PERMISSION] = permission
# IQueryPreprocessor methods
def query_pre_process(self, query_parameters, context=None):
if context is None:
return
def allowed_documents():
#todo: add special case handling for trac_admin and product_owner
for product, perm in self._get_all_user_permissions(context):
if product:
prod_term = query.Term(IndexFields.PRODUCT, product)
else:
prod_term = query.Not(query.Every(IndexFields.PRODUCT))
perm_term = query.Term(IndexFields.REQUIRED_PERMISSION, perm)
yield query.And([prod_term, perm_term])
self.update_security_filter(query_parameters,
allowed=allowed_documents())
def _get_all_user_permissions(self, context):
username = context.req.authname
permissions = []
for perm in instance_for_every_env(self.env, PermissionSystem):
prefix = get_product(perm.env).prefix
for action in self._required_permissions.itervalues():
if perm.check_permission(action, username):
permissions.append((prefix, action))
return permissions
class AuthzSecurityPreprocessor(SecurityPreprocessor):
implements(IQueryPreprocessor)
def __init__(self):
SecurityPreprocessor.__init__(self)
ps = PermissionSystem(self.env)
self.enabled = (is_enabled(self.env, AuthzPolicy)
and any(isinstance(policy, AuthzPolicy)
for policy in ps.policies))
# IQueryPreprocessor methods
def query_pre_process(self, query_parameters, context=None):
if not self.enabled:
return
permissions = self.get_user_permissions(context.req.authname)
allowed_docs, denied_docs = [], []
for product, doc_type, doc_id, perm, denied in permissions:
term_spec = []
if product:
term_spec.append(query.Term(IndexFields.PRODUCT, product))
else:
term_spec.append(query.Not(query.Every(IndexFields.PRODUCT)))
if doc_type != '*':
term_spec.append(query.Term(IndexFields.TYPE, doc_type))
if doc_id != '*':
term_spec.append(query.Term(IndexFields.ID, doc_id))
term_spec.append(query.Term(IndexFields.REQUIRED_PERMISSION, perm))
term_spec = query.And(term_spec)
if denied:
denied_docs.append(term_spec)
else:
allowed_docs.append(term_spec)
self.update_security_filter(query_parameters, allowed_docs, denied_docs)
def get_user_permissions(self, username):
for policy in instance_for_every_env(self.env, AuthzPolicy):
product = get_product(policy.env).prefix
self.refresh_config(policy)
for doc_type, doc_id, perm, denied in self.get_relevant_permissions(policy, username):
yield product, doc_type, doc_id, perm, denied
def get_relevant_permissions(self, policy, username):
ps = PermissionSystem(self.env)
relevant_permissions = set(self._required_permissions.itervalues())
user_permissions = self.get_all_user_permissions(policy, username)
for doc_type, doc_id, permissions in user_permissions:
for deny, perms in groupby(permissions,
key=lambda p: p.startswith('!')):
if deny:
for p in ps.expand_actions([p[1:] for p in perms]):
if p in relevant_permissions:
yield doc_type, doc_id, p, True
else:
for p in ps.expand_actions(perms):
if p in relevant_permissions:
yield doc_type, doc_id, p, False
def get_all_user_permissions(self, policy, username):
relevant_users = self.get_relevant_users(username)
for doc_type, doc_id, section in self.get_all_permissions(policy):
for who, permissions in section.iteritems():
if who in relevant_users or \
who in policy.groups_by_user.get(username, []):
if isinstance(permissions, basestring):
permissions = [permissions]
yield doc_type, doc_id, permissions
def get_all_permissions(self, policy):
for section_name in policy.authz.sections:
if section_name == 'groups':
continue
if '/' in section_name:
continue # advanced permissions are not supported at the moment
type_id = section_name.split('@', 1)[0]
if ':' in type_id:
doc_type, doc_id = type_id.split(':')
else:
doc_type, doc_id = '**'
yield doc_type, doc_id, policy.authz[section_name]
def get_relevant_users(self, username):
if username and username != 'anonymous':
return ['*', 'authenticated', username]
else:
return ['*', 'anonymous']
def refresh_config(self, policy):
if (
policy.authz_file and not policy.authz_mtime
or os.path.getmtime(policy.get_authz_file()) > policy.authz_mtime
):
policy.parse_authz()
class SecurityFilter(query.AndNot):
def __init__(self):
super(SecurityFilter, self).__init__(query.NullQuery, query.NullQuery)
def add_allowed(self, allowed):
if self.a == query.NullQuery:
self.a = query.Or([])
self.a.subqueries.extend(allowed)
self.subqueries = (self.a, self.b)
def add_denied(self, denied):
if self.b == query.NullQuery:
self.b = query.Or([])
self.b.subqueries.extend(denied)
self.subqueries = (self.a, self.b)
def __repr__(self):
r = "%s(allow=%r, deny=%r)" % (self.__class__.__name__,
self.a, self.b)
return r
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/web_ui.py | bloodhound_search/bhsearch/web_ui.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Bloodhound Search user interface."""
import copy
from collections import defaultdict
import pkg_resources
from bhsearch import BHSEARCH_CONFIG_SECTION
import re
from trac.core import Component, implements, TracError
from genshi.builder import tag
from genshi import HTML
from trac.perm import IPermissionRequestor
from trac.search import shorten_result
from trac.config import OrderedExtensionsOption, ListOption, Option, BoolOption
from trac.util.presentation import Paginator
from trac.util.datefmt import format_datetime, user_time
from trac.web import IRequestHandler, IRequestFilter
from trac.util.html import find_element
from trac.web.chrome import (ITemplateProvider,
add_link, add_stylesheet, prevnext_nav,
web_context)
from bhsearch.api import (BloodhoundSearchApi, ISearchParticipant, SCORE, ASC,
DESC, IndexFields, SortInstruction)
from bhsearch.utils import get_global_env, using_multiproduct
from bhsearch.utils.translation import _
from trac.wiki.formatter import extract_link
from multiproduct.env import ProductEnvironment
from multiproduct.web_ui import ProductModule
SEARCH_PERMISSION = 'SEARCH_VIEW'
DEFAULT_RESULTS_PER_PAGE = 10
SEARCH_URL = '/search'
BHSEARCH_URL = '/bhsearch'
SEARCH_URLS_RE = re.compile(r'/(?P<prefix>bh)?search(?P<suffix>.*)')
class RequestParameters(object):
"""
Helper class for parameter parsing and creation of bhsearch specific URLs.
Lifecycle of the class must be per request
"""
QUERY = "q"
PAGE = "page"
TYPE = "type"
NO_QUICK_JUMP = "noquickjump"
PAGELEN = "pagelen"
FILTER_QUERY = "fq"
VIEW = "view"
SORT = "sort"
DEBUG = "debug"
PRODUCT = "product_prefix"
PRODUCT_ID = "productid"
def __init__(self, req, href=None):
# pylint: disable=too-many-branches
self.req = req
self.href = href or req.href
self.original_query = req.args.getfirst(self.QUERY)
if self.original_query is None:
self.query = ""
else:
self.query = self.original_query.strip()
self.no_quick_jump = int(req.args.getfirst(self.NO_QUICK_JUMP, '0'))
self.view = req.args.getfirst(self.VIEW)
self.filter_queries = req.args.getlist(self.FILTER_QUERY)
self.filter_queries = self._remove_possible_duplications(
self.filter_queries)
self.sort_string = req.args.getfirst(self.SORT)
self.sort = self._parse_sort(self.sort_string)
self.pagelen = int(req.args.getfirst(
RequestParameters.PAGELEN,
DEFAULT_RESULTS_PER_PAGE))
self.page = int(req.args.getfirst(self.PAGE, '1'))
self.type = req.args.getfirst(self.TYPE)
self.product = req.args.getfirst(self.PRODUCT)
self.debug = int(req.args.getfirst(self.DEBUG, '0'))
self.params = {
RequestParameters.FILTER_QUERY: []
}
if self.original_query is not None:
self.params[self.QUERY] = self.original_query
if self.no_quick_jump > 0:
self.params[self.NO_QUICK_JUMP] = self.no_quick_jump
if self.view is not None:
self.params[self.VIEW] = self.view
if self.pagelen != DEFAULT_RESULTS_PER_PAGE:
self.params[self.PAGELEN] = self.pagelen
if self.page > 1:
self.params[self.PAGE] = self.page
if self.type:
self.params[self.TYPE] = self.type
if self.product is not None:
self.params[self.PRODUCT] = self.product
if self.filter_queries:
self.params[RequestParameters.FILTER_QUERY] = self.filter_queries
if self.sort_string:
self.params[RequestParameters.SORT] = self.sort_string
if self.debug:
self.params[RequestParameters.DEBUG] = self.debug
def _parse_sort(self, sort_string):
if not sort_string:
return None
sort_terms = sort_string.split(",")
sort = []
for term in sort_terms:
term = term.strip()
if not term:
continue
term_parts = term.split()
parts_count = len(term_parts)
if parts_count == 1:
sort.append(SortInstruction(term_parts[0], ASC))
elif parts_count == 2:
sort.append(SortInstruction(term_parts[0], term_parts[1]))
else:
raise TracError("Invalid sort term %s " % term)
return sort if sort else None
def _remove_possible_duplications(self, parameters_list):
seen = set()
return [parameter for parameter in parameters_list
if parameter not in seen and not seen.add(parameter)]
def create_href(
self,
page=None,
type=None,
skip_type=False,
skip_page=False,
additional_filter=None,
force_filters=None,
view=None,
skip_view=False,
sort=None,
skip_sort=False,
query=None,
skip_query=False,
product=None,
skip_product=False,
):
# pylint: disable=too-many-locals,too-many-branches
params = copy.deepcopy(self.params)
if skip_sort:
self._delete_if_exists(params, self.SORT)
elif sort:
params[self.SORT] = self._create_sort_expression(sort)
#noquickjump parameter should be always set to 1 for urls
params[self.NO_QUICK_JUMP] = 1
if skip_view:
self._delete_if_exists(params, self.VIEW)
elif view:
params[self.VIEW] = view
if skip_page:
self._delete_if_exists(params, self.PAGE)
elif page:
params[self.PAGE] = page
if skip_type:
self._delete_if_exists(params, self.TYPE)
elif type:
params[self.TYPE] = type
if additional_filter and\
additional_filter not in params[self.FILTER_QUERY]:
params[self.FILTER_QUERY].append(additional_filter)
elif force_filters is not None:
params[self.FILTER_QUERY] = force_filters
if skip_query:
self._delete_if_exists(params, self.QUERY)
elif query is not None:
params[self.QUERY] = query
if skip_product:
self._delete_if_exists(params, self.PRODUCT)
elif product is not None:
params[self.PRODUCT] = product
return self.href.bhsearch(**params)
def _create_sort_expression(self, sort):
"""
Accepts single sort instruction e.g. SortInstruction(field, ASC) or
list of sort instructions e.g.
[SortInstruction(field1, ASC), SortInstruction(field2, DESC)]
"""
if not sort:
return None
if isinstance(sort, SortInstruction):
return sort.build_sort_expression()
return ", ".join([item.build_sort_expression() for item in sort])
def _delete_if_exists(self, params, name):
if name in params:
del params[name]
class BloodhoundSearchModule(Component):
"""Main search page"""
implements(IPermissionRequestor, IRequestHandler,
ITemplateProvider, IRequestFilter
# IWikiSyntaxProvider #todo: implement later
)
search_participants = OrderedExtensionsOption(
'bhsearch',
'search_participants',
ISearchParticipant,
"TicketSearchParticipant, WikiSearchParticipant",
include_missing=True
)
prefix = "all"
default_grid_fields = [
IndexFields.PRODUCT,
IndexFields.ID,
IndexFields.TYPE,
IndexFields.TIME,
IndexFields.AUTHOR,
IndexFields.CONTENT,
]
default_facets = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_facets',
default=",".join([IndexFields.PRODUCT, IndexFields.TYPE]),
doc="""Default facets applied to search view of all resources""",
doc_domain='bhsearch')
default_view = Option(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_view',
doc="""If true, show grid as default view for specific resource in
Bloodhound Search results""", doc_domain='bhsearch')
all_grid_fields = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_grid_fields',
default=",".join(default_grid_fields),
doc="""Default fields for grid view for specific resource""",
doc_domain='bhsearch')
default_search = BoolOption(
BHSEARCH_CONFIG_SECTION,
'is_default',
default=False,
doc="""Searching from quicksearch uses bhsearch.""",
doc_domain='bhsearch')
redirect_enabled = BoolOption(
BHSEARCH_CONFIG_SECTION,
'enable_redirect',
default=False,
doc="""Redirect links pointing to trac search to bhsearch""",
doc_domain='bhsearch')
global_quicksearch = BoolOption(
BHSEARCH_CONFIG_SECTION,
'global_quicksearch',
default=True,
doc="""Quicksearch searches all products, even when used
in product env.""", doc_domain='bhsearch')
query_suggestions_enabled = BoolOption(
BHSEARCH_CONFIG_SECTION,
'query_suggestions',
default=True,
doc="""Display query suggestions.""", doc_domain='bhsearch'
)
# IPermissionRequestor methods
def get_permission_actions(self):
return [SEARCH_PERMISSION]
# IRequestHandler methods
def match_request(self, req):
return re.match('^%s' % BHSEARCH_URL, req.path_info) is not None
def process_request(self, req):
req.perm.assert_permission(SEARCH_PERMISSION)
if self._is_opensearch_request(req):
return ('opensearch.xml', {},
'application/opensearchdescription+xml')
request_context = RequestContext(
self.env,
req,
self.search_participants,
self.default_view,
self.all_grid_fields,
self.default_facets,
self.global_quicksearch,
self.query_suggestions_enabled,
)
if request_context.requires_redirect:
req.redirect(request_context.parameters.create_href(), True)
# compatibility with legacy search
req.search_query = request_context.parameters.query
query_result = BloodhoundSearchApi(self.env).query(
request_context.parameters.query,
pagenum=request_context.page,
pagelen=request_context.pagelen,
sort=request_context.sort,
fields=request_context.fields,
facets=request_context.facets,
filter=request_context.query_filter,
highlight=True,
context=request_context,
)
request_context.process_results(query_result)
return self._return_data(req, request_context.data)
def _is_opensearch_request(self, req):
return req.path_info == BHSEARCH_URL + '/opensearch'
def _return_data(self, req, data):
add_stylesheet(req, 'common/css/search.css')
return 'bhsearch.html', data, None
# ITemplateProvider methods
def get_htdocs_dirs(self):
# return [('bhsearch',
# pkg_resources.resource_filename(__name__, 'htdocs'))]
return []
def get_templates_dirs(self):
return [pkg_resources.resource_filename(__name__, 'templates')]
# IRequestFilter methods
def pre_process_request(self, req, handler):
if SEARCH_URLS_RE.match(req.path_info):
if self.redirect_enabled:
return self
return handler
def post_process_request(self, req, template, data, content_type):
if data is None:
return template, data, content_type
if self.redirect_enabled:
data['search_handler'] = req.href.bhsearch()
elif req.path_info.startswith(SEARCH_URL):
data['search_handler'] = req.href.search()
elif self.default_search or req.path_info.startswith(BHSEARCH_URL):
data['search_handler'] = req.href.bhsearch()
else:
data['search_handler'] = req.href.search()
return template, data, content_type
class RequestContext(object):
DATA_ACTIVE_FILTER_QUERIES = 'active_filter_queries'
DATA_ACTIVE_PRODUCT = 'active_product'
DATA_ACTIVE_QUERY = 'active_query'
DATA_BREADCRUMBS_TEMPLATE = 'resourcepath_template'
DATA_HEADERS = "headers"
DATA_ALL_VIEWS = "all_views"
DATA_VIEW = "view"
DATA_VIEW_GRID = "grid"
DATA_FACET_COUNTS = 'facet_counts'
DATA_DEBUG = 'debug'
DATA_PAGE_HREF = 'page_href'
DATA_RESULTS = 'results'
DATA_PRODUCT_LIST = 'search_product_list'
DATA_QUERY = 'query'
DATA_QUICK_JUMP = "quickjump"
DATA_QUERY_SUGGESTION = 'query_suggestion'
DATA_SEARCH_EXTRAS = 'extra_search_fields'
#bhsearch may support more pluggable views later
VIEWS_SUPPORTED = (
(None, "Free text"),
(DATA_VIEW_GRID, "Grid"),
)
VIEWS_WITH_KNOWN_FIELDS = [DATA_VIEW_GRID]
OBLIGATORY_FIELDS_TO_SELECT = [IndexFields.ID, IndexFields.TYPE]
DEFAULT_SORT = [SortInstruction(SCORE, ASC), SortInstruction("time", DESC)]
def __init__(
self,
env,
req,
search_participants,
default_view,
all_grid_fields,
default_facets,
global_quicksearch,
query_suggestions,
):
self.env = env
self.req = req
self.requires_redirect = False
self._handle_multiproduct_parameters(req, global_quicksearch)
self.parameters = RequestParameters(
req,
href=get_global_env(self.env).href
)
self.data = {
self.DATA_QUERY: self.parameters.query,
self.DATA_SEARCH_EXTRAS: [],
}
self.search_participants = search_participants
self.default_view = default_view
self.all_grid_fields = all_grid_fields
self.default_facets = default_facets
self.view = None
self.page = self.parameters.page
self.pagelen = self.parameters.pagelen
self.query_suggestions = query_suggestions
if self.parameters.sort:
self.sort = self.parameters.sort
else:
self.sort = self.DEFAULT_SORT
self.allowed_participants, self.sorted_participants = \
self._get_allowed_participants(req)
if self.parameters.type in self.allowed_participants:
self.active_type = self.parameters.type
self.active_participant = self.allowed_participants[
self.active_type]
else:
self.active_type = None
self.active_participant = None
self.active_product = self.parameters.product
self._prepare_active_type()
self._prepare_hidden_search_fields()
self._prepare_quick_jump()
# Compatibility with trac search
self._process_legacy_type_filters(req, search_participants)
if not req.path_info.startswith(BHSEARCH_URL):
self.requires_redirect = True
self.fields = self._prepare_fields_and_view()
self.query_filter = self._prepare_query_filter()
self.facets = self._prepare_facets()
def _handle_multiproduct_parameters(self, req, global_quicksearch):
if not using_multiproduct(self.env):
return
if self.env.parent is not None:
if not global_quicksearch:
req.args[RequestParameters.PRODUCT] = \
self.env.product.prefix
self.requires_redirect = True
def _get_allowed_participants(self, req):
allowed_participants = {}
ordered_participants = []
for participant in self.search_participants:
if participant.is_allowed(req):
allowed_participants[
participant.get_participant_type()] = participant
ordered_participants.append(participant)
return allowed_participants, ordered_participants
def _prepare_active_type(self):
active_type = self.parameters.type
if active_type and active_type not in self.allowed_participants:
raise TracError(_("Unsupported resource type: '%(name)s'",
name=active_type))
def _prepare_hidden_search_fields(self):
if self.active_type:
self.data[self.DATA_SEARCH_EXTRAS].append(
(RequestParameters.TYPE, self.active_type)
)
if self.parameters.product:
self.data[self.DATA_SEARCH_EXTRAS].append(
(RequestParameters.PRODUCT, self.parameters.product)
)
if self.parameters.view:
self.data[self.DATA_SEARCH_EXTRAS].append(
(RequestParameters.VIEW, self.parameters.view)
)
if self.parameters.sort:
self.data[self.DATA_SEARCH_EXTRAS].append(
(RequestParameters.SORT, self.parameters.sort_string)
)
for filter_query in self.parameters.filter_queries:
self.data[self.DATA_SEARCH_EXTRAS].append(
(RequestParameters.FILTER_QUERY, filter_query)
)
def _prepare_quick_jump(self):
if not self.parameters.query:
return
check_result = self._check_quickjump(
self.req,
self.parameters.query)
if check_result:
self.data[self.DATA_QUICK_JUMP] = check_result
#the method below is "copy/paste" from trac search/web_ui.py
def _check_quickjump(self, req, kwd):
"""Look for search shortcuts"""
# pylint: disable=maybe-no-member
noquickjump = int(req.args.get('noquickjump', '0'))
# Source quickjump FIXME: delegate to ISearchSource.search_quickjump
quickjump_href = None
if kwd[0] == '/':
quickjump_href = req.href.browser(kwd)
name = kwd
description = _('Browse repository path %(path)s', path=kwd)
else:
context = web_context(req, 'search')
link = find_element(extract_link(self.env, context, kwd), 'href')
if link is not None:
quickjump_href = link.attrib.get('href')
name = link.children
description = link.attrib.get('title', '')
if quickjump_href:
# Only automatically redirect to local quickjump links
base_path = req.base_path.replace('@', '%40')
redirect_href = quickjump_href.replace('@', '%40')
if not redirect_href.startswith(base_path or '/'):
noquickjump = True
if noquickjump:
return {'href': quickjump_href, 'name': tag.EM(name),
'description': description}
else:
req.redirect(quickjump_href)
def _prepare_fields_and_view(self):
self._add_views_selector()
self.view = self._get_view()
if self.view:
self.data[self.DATA_VIEW] = self.view
fields_to_select = None
if self.view in self.VIEWS_WITH_KNOWN_FIELDS:
if self.active_participant:
fields_in_view = self.active_participant.\
get_default_view_fields(self.view)
elif self.view == self.DATA_VIEW_GRID:
fields_in_view = self.all_grid_fields
else:
raise TracError("Unsupported view: %s" % self.view)
self.data[self.DATA_HEADERS] = [self._create_headers_item(field)
for field in fields_in_view]
fields_to_select = self._add_obligatory_fields(
fields_in_view)
return fields_to_select
def _add_views_selector(self):
active_view = self.parameters.view
all_views = []
for view, label in self.VIEWS_SUPPORTED:
all_views.append(dict(
label=_(label),
href=self.parameters.create_href(
view=view, skip_view=(view is None)),
is_active=(view == active_view)
))
self.data[self.DATA_ALL_VIEWS] = all_views
def _get_view(self):
view = self.parameters.view
if view is None:
if self.active_participant:
view = self.active_participant.get_default_view()
else:
view = self.default_view
if view is not None:
view = view.strip().lower()
if view == "":
view = None
return view
def _add_obligatory_fields(self, fields_in_view):
fields_to_select = list(fields_in_view)
for obligatory_field in self.OBLIGATORY_FIELDS_TO_SELECT:
if obligatory_field is not fields_to_select:
fields_to_select.append(obligatory_field)
return fields_to_select
def _create_headers_item(self, field):
current_sort_direction = self._get_current_sort_direction_for_field(
field)
href_sort_direction = DESC if current_sort_direction == ASC else ASC
return dict(
name=field,
href=self.parameters.create_href(
skip_page=True,
sort=SortInstruction(field, href_sort_direction)
),
#TODO:add translated column label. Now it is really temporary
# workaround
label=field,
sort=current_sort_direction,
)
def _get_current_sort_direction_for_field(self, field):
if self.sort and len(self.sort) == 1:
single_sort = self.sort[0]
if single_sort.field == field:
return single_sort.order
return None
def _prepare_query_filter(self):
query_filters = list(self.parameters.filter_queries)
if self.active_type:
query_filters.append(
self._create_term_expression(
IndexFields.TYPE, self.active_type))
if self.active_product is not None:
query_filters.append(self._create_term_expression(
IndexFields.PRODUCT, self.active_product or None)
)
return query_filters
def _create_term_expression(self, field, field_value):
if field_value is None:
query = "NOT (%s:*)" % field
elif isinstance(field_value, basestring):
query = '%s:"%s"' % (field, field_value)
else:
query = '%s:%s' % (field, field_value)
return query
def _prepare_facets(self):
#TODO: add possibility of specifying facets in query parameters
if self.active_participant:
facets = self.active_participant.get_default_facets()
else:
facets = self.default_facets
return facets
def _process_legacy_type_filters(self, req, search_participants):
legacy_type_filters = [sp.get_participant_type()
for sp in search_participants
if sp.get_participant_type() in req.args]
if legacy_type_filters:
params = self.parameters.params
if len(legacy_type_filters) == 1:
self.parameters.type = params[RequestParameters.TYPE] = \
legacy_type_filters[0]
else:
filter_queries = self.parameters.filter_queries
if params[RequestParameters.FILTER_QUERY] is not filter_queries:
params[RequestParameters.FILTER_QUERY] = filter_queries
filter_queries.append(
'type:(%s)' % ' OR '.join(legacy_type_filters)
)
self.requires_redirect = True
def _process_doc(self, doc):
ui_doc = dict(doc)
if doc.get('product'):
env = ProductEnvironment(self.env, doc['product'])
product_href = ProductEnvironment.resolve_href(env, self.env)
# pylint: disable=too-many-function-args
ui_doc["href"] = product_href(doc['type'], doc['id'])
else:
ui_doc["href"] = self.req.href(doc['type'], doc['id'])
if doc['content']:
ui_doc['content'] = shorten_result(doc['content'])
if doc['time']:
ui_doc['date'] = user_time(self.req, format_datetime, doc['time'])
is_free_text_view = self.view is None
if is_free_text_view:
participant = self.allowed_participants[doc['type']]
ui_doc['title'] = participant.format_search_results(doc)
return ui_doc
def _prepare_results(self, result_docs, hits):
ui_docs = [self._process_doc(doc) for doc in result_docs]
results = Paginator(
ui_docs,
self.page - 1,
self.pagelen,
hits)
self._prepare_shown_pages(results)
results.current_page = {'href': None,
'class': 'current',
'string': str(results.page + 1),
'title': None}
parameters = self.parameters
if results.has_next_page:
next_href = parameters.create_href(page=parameters.page + 1)
add_link(self.req, 'next', next_href, _('Next Page'))
if results.has_previous_page:
prev_href = parameters.create_href(page=parameters.page - 1)
add_link(self.req, 'prev', prev_href, _('Previous Page'))
self.data[self.DATA_RESULTS] = results
prevnext_nav(self.req, _('Previous'), _('Next'))
def _prepare_shown_pages(self, results):
shown_pages = results.get_shown_pages(self.pagelen)
page_data = []
for shown_page in shown_pages:
page_href = self.parameters.create_href(page=shown_page)
page_data.append([page_href, None, str(shown_page),
'page ' + str(shown_page)])
fields = ['href', 'class', 'string', 'title']
results.shown_pages = [dict(zip(fields, p)) for p in page_data]
def process_results(self, query_result):
docs = self._prepare_docs(query_result.docs,
query_result.highlighting)
self._prepare_results(docs, query_result.hits)
self._prepare_result_facet_counts(query_result.facets)
self._prepare_breadcrumbs()
self._prepare_query_suggestion(query_result.query_suggestion)
self.data[self.DATA_DEBUG] = query_result.debug
if self.parameters.debug:
self.data[self.DATA_DEBUG]['enabled'] = True
self.data[self.DATA_SEARCH_EXTRAS].append(('debug', '1'))
self.data[self.DATA_PAGE_HREF] = self.parameters.create_href()
def _prepare_result_facet_counts(self, result_facets):
"""
Sample query_result.facets content returned by query
{
'component': {None:2},
'milestone': {None:1, 'm1':1},
}
returned facet_count contains href parameters:
{
'component': {None: {'count':2, href:'...'},
'milestone': {
None: {'count':1,, href:'...'},
'm1':{'count':1, href:'...'}
},
}
"""
facet_counts = []
if result_facets:
for field in self.facets:
if field == IndexFields.PRODUCT and \
not using_multiproduct(self.env):
continue
facets_dict = result_facets.get(field, {})
per_field_dict = dict()
for field_value, count in facets_dict.iteritems():
if field == IndexFields.TYPE:
href = self.parameters.create_href(
skip_page=True,
force_filters=[],
type=field_value)
elif field == IndexFields.PRODUCT:
href = self.parameters.create_href(
skip_page=True,
product=field_value or u'',
)
else:
href = self.parameters.create_href(
skip_page=True,
additional_filter=self._create_term_expression(
field,
field_value)
)
per_field_dict[field_value] = dict(
count=count,
href=href
)
facet_counts.append((_(field), per_field_dict))
self.data[self.DATA_FACET_COUNTS] = facet_counts
def _prepare_docs(self, docs, highlights):
new_docs = []
for doc, highlight in zip(docs, highlights):
doc = defaultdict(str, doc)
for field in highlight.iterkeys():
highlighted_field = 'hilited_%s' % field
if highlight[field]:
fragment = self._create_genshi_fragment(highlight[field])
doc[highlighted_field] = fragment
else:
doc[highlighted_field] = ''
new_docs.append(doc)
return new_docs
def _create_genshi_fragment(self, html_fragment):
return tag(HTML(html_fragment))
def _prepare_breadcrumbs(self):
self._prepare_breadcrumbs_template()
self._prepare_product_breadcrumb()
self._prepare_query_filter_breadcrumbs()
def _prepare_breadcrumbs_template(self):
self.data[self.DATA_BREADCRUMBS_TEMPLATE] = 'bhsearch_breadcrumbs.html'
def _prepare_product_breadcrumb(self):
if not using_multiproduct(self.env):
return
product_search = lambda x: self.parameters.create_href(product=x)
all_products_search = self.parameters.create_href(skip_product=True)
global_product = [(u'', _(u'Global product'), product_search(u''))]
products = \
ProductModule.get_product_list(self.env, self.req, product_search)
all_products = [(None, _(u'All products'), all_products_search)]
search_product_list = global_product + products + all_products
# pylint: disable=unused-variable
for prefix, name, url in search_product_list:
if prefix == self.active_product:
self.data[self.DATA_ACTIVE_PRODUCT] = name
break
else:
self.data[self.DATA_ACTIVE_PRODUCT] = self.active_product
self.data[self.DATA_PRODUCT_LIST] = search_product_list
def _prepare_query_filter_breadcrumbs(self):
current_filters = self.parameters.filter_queries
def remove_filter_from_list(filter_to_remove):
new_filters = list(current_filters)
new_filters.remove(filter_to_remove)
return new_filters
if self.active_type:
type_query = self._create_term_expression('type', self.active_type)
type_filters = [dict(
href=self.parameters.create_href(skip_type=True,
force_filters=[]),
label=unicode(self.active_type).capitalize(),
query=type_query,
)]
else:
type_filters = []
active_filter_queries = [
dict(
href=self.parameters.create_href(
force_filters=remove_filter_from_list(filter_query)
),
label=filter_query,
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | true |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/admin.py | bloodhound_search/bhsearch/admin.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Administration commands for Bloodhound Search."""
from trac.core import Component, implements
from trac.admin import IAdminCommandProvider
from bhsearch.api import BloodhoundSearchApi
class BloodhoundSearchAdmin(Component):
"""Bloodhound Search administration component."""
implements(IAdminCommandProvider)
# IAdminCommandProvider methods
def get_admin_commands(self):
yield ('bhsearch rebuild', '',
'Rebuild Bloodhound Search index',
None, BloodhoundSearchApi(self.env).rebuild_index)
yield ('bhsearch optimize', '',
'Optimize Bloodhound search index',
None, BloodhoundSearchApi(self.env).optimize)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/query_suggestion.py | bloodhound_search/bhsearch/query_suggestion.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.core import Component, implements
from bhsearch.api import IDocIndexPreprocessor, IndexFields
class SuggestionFields(IndexFields):
SUMMARY = 'summary'
BASKET = 'query_suggestion_basket'
class QuerySuggestionPreprocessor(Component):
implements(IDocIndexPreprocessor)
suggestion_fields = [
IndexFields.NAME,
IndexFields.CONTENT,
SuggestionFields.SUMMARY,
]
# IDocIndexPreprocessor methods
def pre_process(self, doc):
basket = u' '.join(doc.get(field, '')
for field in self.suggestion_fields)
doc[SuggestionFields.BASKET] = basket
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/query_parser.py | bloodhound_search/bhsearch/query_parser.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Provides Bloodhound Search query parsing functionality"""
from bhsearch.api import IQueryParser, IMetaKeywordParser, ISearchParticipant
from bhsearch.whoosh_backend import WhooshBackend
from trac.config import ExtensionPoint
from trac.core import Component, implements
from whoosh import query, qparser
from whoosh.qparser import MultifieldParser
class MetaKeywordNode(qparser.GroupNode):
def __init__(self, group_node=None, **kwargs):
nodes = group_node.nodes if group_node else []
super(MetaKeywordNode, self).__init__(nodes, kwargs=kwargs)
class MetaKeywordPlugin(qparser.TaggingPlugin):
priority = 0
expr = r"[$](?P<text>[^ \t\r\n]+)(?= |$|\))"
nodetype = qparser.syntax.WordNode
def __init__(self, meta_keyword_parsers=(), context=None):
super(MetaKeywordPlugin, self).__init__()
self.meta_keyword_parsers = meta_keyword_parsers
self.context = context
def match(self, parser, text, pos):
match = qparser.TaggingPlugin.match(self, parser, text, pos)
if match is None:
return
candidate = match.text
for meta_keyword_parser in self.meta_keyword_parsers:
expanded_meta_keyword = meta_keyword_parser.match(candidate,
self.context)
if expanded_meta_keyword is not None:
node = MetaKeywordNode(parser.tag(expanded_meta_keyword))
return node.set_range(match.startchar, match.endchar)
def filters(self, parser):
# must execute before GroupPlugin with priority 0
return [(self.unroll_meta_keyword_nodes, -100)]
def unroll_meta_keyword_nodes(self, parser, group):
newgroup = group.empty_copy()
for node in group:
if isinstance(node, MetaKeywordNode):
newgroup.extend(self.unroll_meta_keyword_nodes(parser, node))
elif isinstance(node, qparser.GroupNode):
newgroup.append(self.unroll_meta_keyword_nodes(parser, node))
else:
newgroup.append(node)
return newgroup
class DefaultQueryParser(Component):
implements(IQueryParser)
#todo: make field boost configurable e.g. read from config setting.
#This is prototype implementation ,the fields boost must be tuned later
field_boosts = dict(
id = 6,
name = 6,
type = 2,
summary = 5,
author = 3,
milestone = 2,
keywords = 2,
component = 2,
status = 2,
content = 1,
changes = 1,
message = 1,
query_suggestion_basket = 0,
relations = 1,
)
meta_keyword_parsers = ExtensionPoint(IMetaKeywordParser)
def parse(self, query_string, context=None):
parser = self._create_parser(context)
query_string = query_string.strip()
if query_string == "" or query_string == "*" or query_string == "*:*":
return query.Every()
query_string = unicode(query_string)
parsed_query = parser.parse(query_string)
parsed_query.original_query_string = query_string
return parsed_query
def parse_filters(self, filters):
"""Parse query filters"""
if not filters:
return None
parsed_filters = [self._parse_filter(filter) for filter in filters]
return query.And(parsed_filters).normalize()
def _parse_filter(self, filter):
return self.parse(unicode(filter))
def _create_parser(self, context):
parser = MultifieldParser(
self.field_boosts.keys(),
WhooshBackend.SCHEMA,
fieldboosts=self.field_boosts
)
parser.add_plugin(
MetaKeywordPlugin(meta_keyword_parsers=self.meta_keyword_parsers,
context=context)
)
return parser
class DocTypeMetaKeywordParser(Component):
implements(IMetaKeywordParser)
search_participants = ExtensionPoint(ISearchParticipant)
def match(self, text, context):
# pylint: disable=unused-argument
documents = [p.get_participant_type()
for p in self.search_participants]
if text in documents:
return u'type:%s' % text
class ResolvedMetaKeywordParser(Component):
implements(IMetaKeywordParser)
def match(self, text, context):
# pylint: disable=unused-argument
if text == u'resolved':
return u'status:(resolved OR closed)'
class UnResolvedMetaKeywordParser(Component):
implements(IMetaKeywordParser)
def match(self, text, context):
# pylint: disable=unused-argument
if text == u'unresolved':
return u'NOT $resolved'
class MeMetaKeywordParser(Component):
implements(IMetaKeywordParser)
def match(self, text, context):
if text == u'me':
username = unicode(context.req.authname)
return username
class MyMetaKeywordParser(Component):
implements(IMetaKeywordParser)
def match(self, text, context):
# pylint: disable=unused-argument
if text == u'my':
return u'owner:$me'
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/__init__.py | bloodhound_search/bhsearch/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Improved search and query plugin for Apache(TM) Bloodhound
Add free text search and query plugin to Bloodhound sites.
"""
# Ignore errors to avoid Internal Server Errors
from trac.core import TracError
TracError.__str__ = lambda self: unicode(self).encode('ascii', 'ignore')
try:
# pylint: disable=wildcard-import
from bhsearch import *
msg = 'Ok'
except Exception, exc:
# raise
msg = "Exception %s raised: '%s'" % (exc.__class__.__name__, str(exc))
BHSEARCH_CONFIG_SECTION = "bhsearch"
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/whoosh_backend.py | bloodhound_search/bhsearch/whoosh_backend.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Whoosh specific backend for Bloodhound Search plugin."""
import os
from datetime import datetime
from trac.core import Component, implements, TracError
from trac.config import Option, IntOption
from trac.env import ISystemInfoProvider
from trac.util.datefmt import utc
import whoosh
from whoosh import index, analysis
from whoosh.collectors import FilterCollector
from whoosh.fields import Schema, ID, DATETIME, KEYWORD, TEXT
from whoosh.writing import AsyncWriter
from bhsearch import BHSEARCH_CONFIG_SECTION
from bhsearch.api import ISearchBackend, DESC, QueryResult, SCORE
from bhsearch.security import SecurityPreprocessor
from bhsearch.utils import get_global_env
UNIQUE_ID = "unique_id"
class WhooshBackend(Component):
"""
Implements Whoosh SearchBackend interface
"""
implements(ISearchBackend, ISystemInfoProvider)
index_dir_setting = Option(
BHSEARCH_CONFIG_SECTION,
'whoosh_index_dir',
default='whoosh_index',
doc="""Relative path is resolved relatively to the
directory of the environment.""", doc_domain='bhsearch')
advanced_security = Option(
BHSEARCH_CONFIG_SECTION,
'advanced_security',
default=False,
doc="Check view permission for each document when retrieving results.",
doc_domain='bhsearch'
)
max_fragment_size = IntOption(
BHSEARCH_CONFIG_SECTION,
'max_fragment_size',
default=240,
doc="The maximum number of characters allowed in a fragment.",
doc_domain='bhsearch')
fragment_surround = IntOption(
BHSEARCH_CONFIG_SECTION,
'fragment_surround',
default=60,
doc="""The number of extra characters of context to add both before
the first matched term and after the last matched term.""",
doc_domain='bhsearch')
#This is schema prototype. It will be changed later
#TODO: add other fields support, add dynamic field support.
#Schema must be driven by index participants
SCHEMA = Schema(
unique_id=ID(stored=True, unique=True),
id=ID(stored=True),
type=ID(stored=True),
product=ID(stored=True),
milestone=ID(stored=True),
time=DATETIME(stored=True),
due=DATETIME(stored=True),
completed=DATETIME(stored=True),
author=ID(stored=True),
component=ID(stored=True),
status=ID(stored=True),
resolution=ID(stored=True),
keywords=KEYWORD(scorable=True),
summary=TEXT(stored=True,
analyzer=analysis.StandardAnalyzer(stoplist=None)),
content=TEXT(stored=True,
analyzer=analysis.StandardAnalyzer(stoplist=None)),
changes=TEXT(analyzer=analysis.StandardAnalyzer(stoplist=None)),
owner=TEXT(stored=True,
analyzer=analysis.SimpleAnalyzer()),
repository=TEXT(stored=True,
analyzer=analysis.SimpleAnalyzer()),
revision=TEXT(stored=True,
analyzer=analysis.SimpleAnalyzer()),
message=TEXT(stored=True,
analyzer=analysis.SimpleAnalyzer()),
required_permission=ID(),
name=TEXT(stored=True,
analyzer=analysis.SimpleAnalyzer()),
query_suggestion_basket=TEXT(analyzer=analysis.SimpleAnalyzer(),
spelling=True),
relations=KEYWORD(lowercase=True, commas=True),
)
def __init__(self):
self.index_dir = self.index_dir_setting
if not os.path.isabs(self.index_dir):
self.index_dir = os.path.join(get_global_env(self.env).path,
self.index_dir)
if index.exists_in(self.index_dir):
self.index = index.open_dir(self.index_dir)
else:
self.index = None
# ISystemInfoProvider methods
def get_system_info(self):
yield 'Whoosh', whoosh.versionstring()
# ISearchBackend methods
def start_operation(self):
return self._create_writer()
def _create_writer(self):
return AsyncWriter(self.index)
def add_doc(self, doc, operation_context=None):
"""Add any type of document index.
The contents should be a dict with fields matching the search schema.
The only required fields are type and id, everything else is optional.
"""
writer = operation_context
is_local_writer = False
if writer is None:
is_local_writer = True
writer = self._create_writer()
self._reformat_doc(doc)
doc[UNIQUE_ID] = self._create_unique_id(doc.get("product", ''),
doc["type"],
doc["id"])
self.log.debug("Doc to index: %s", doc)
try:
writer.update_document(**doc)
if is_local_writer:
writer.commit()
except:
if is_local_writer:
writer.cancel()
raise
def _reformat_doc(self, doc):
"""
Strings must be converted unicode format accepted by Whoosh.
"""
for key, value in doc.items():
if key is None:
del doc[None]
elif value is None:
del doc[key]
elif isinstance(value, basestring) and value == "":
del doc[key]
else:
doc[key] = self._to_whoosh_format(value)
def delete_doc(self, product, doc_type, doc_id, operation_context=None):
unique_id = self._create_unique_id(product, doc_type, doc_id)
self.log.debug('Removing document from the index: %s', unique_id)
writer = operation_context
is_local_writer = False
if writer is None:
is_local_writer = True
writer = self._create_writer()
try:
writer.delete_by_term(UNIQUE_ID, unique_id)
if is_local_writer:
writer.commit()
except:
if is_local_writer:
writer.cancel()
raise
def optimize(self):
writer = AsyncWriter(self.index)
writer.commit(optimize=True)
def is_index_outdated(self):
return self.index is None or not self.index.schema == self.SCHEMA
def recreate_index(self):
self.log.info('Creating Whoosh index in %s' % self.index_dir)
self._make_dir_if_not_exists()
self.index = index.create_in(self.index_dir, schema=self.SCHEMA)
return self.index
def query(self,
query,
query_string=None,
sort=None,
fields=None,
filter=None,
facets=None,
pagenum=1,
pagelen=20,
highlight=False,
highlight_fields=None,
context=None):
# pylint: disable=too-many-locals
with self.index.searcher() as searcher:
self._apply_advanced_security(searcher, context)
highlight_fields = self._prepare_highlight_fields(highlight,
highlight_fields)
sortedby = self._prepare_sortedby(sort)
#TODO: investigate how faceting is applied to multi-value fields
#e.g. keywords. For now, just pass facets lit to Whoosh API
#groupedby = self._prepare_groupedby(facets)
groupedby = facets
query_parameters = dict(
query=query,
pagenum=pagenum,
pagelen=pagelen,
sortedby=sortedby,
groupedby=groupedby,
maptype=whoosh.sorting.Count,
filter=filter,
)
self.env.log.debug("Whoosh query to execute: %s",
query_parameters)
raw_page = searcher.search_page(**query_parameters)
results = self._process_results(raw_page,
fields,
highlight_fields,
query_parameters)
if query_string is not None:
c = searcher.correct_query(query, query_string)
results.query_suggestion = c.string
try:
actual_query = unicode(query.simplify(searcher))
results.debug['actual_query'] = actual_query
# pylint: disable=bare-except
except:
# Simplify has a bug that causes it to fail sometimes.
pass
return results
def _apply_advanced_security(self, searcher, context=None):
if not self.advanced_security:
return
old_collector = searcher.collector
security_processor = SecurityPreprocessor(self.env)
def check_permission(doc):
return security_processor.check_permission(doc, context)
def collector(*args, **kwargs):
c = old_collector(*args, **kwargs)
if isinstance(c, FilterCollector):
c = AdvancedFilterCollector(
c.child, c.allow, c.restrict, check_permission
)
else:
c = AdvancedFilterCollector(
c, None, None, check_permission
)
return c
searcher.collector = collector
def _create_unique_id(self, product, doc_type, doc_id):
if product:
return u"%s:%s:%s" % (product, doc_type, doc_id)
else:
return u"%s:%s" % (doc_type, doc_id)
def _to_whoosh_format(self, value):
if isinstance(value, basestring):
value = unicode(value)
elif isinstance(value, datetime):
value = self._convert_date_to_tz_naive_utc(value)
return value
def _convert_date_to_tz_naive_utc(self, value):
"""Convert datetime to naive utc datetime
Whoosh can not read from index datetime values passed from Trac with
tzinfo=trac.util.datefmt.FixedOffset because of non-empty
constructor of FixedOffset"""
if value.tzinfo:
utc_time = value.astimezone(utc)
value = utc_time.replace(tzinfo=None)
return value
def _from_whoosh_format(self, value):
if isinstance(value, datetime):
value = utc.localize(value)
return value
def _prepare_groupedby(self, facets):
if not facets:
return None
groupedby = whoosh.sorting.Facets()
for facet_name in facets:
groupedby.add_field(
facet_name,
allow_overlap=True,
maptype=whoosh.sortingwhoosh.Count)
return groupedby
def _prepare_sortedby(self, sort):
if not sort:
return None
sortedby = []
for sort_instruction in sort:
field = sort_instruction.field
order = sort_instruction.order
if field.lower() == SCORE:
if self._is_desc(order):
#We can implement tis later by our own ScoreFacet with
# "score DESC" support
raise TracError(
"Whoosh does not support DESC score ordering.")
sort_condition = whoosh.sorting.ScoreFacet()
else:
sort_condition = whoosh.sorting.FieldFacet(
field,
reverse=self._is_desc(order))
sortedby.append(sort_condition)
return sortedby
def _prepare_highlight_fields(self, highlight, highlight_fields):
if not highlight:
return ()
if not highlight_fields:
highlight_fields = self._all_highlightable_fields()
return highlight_fields
def _all_highlightable_fields(self):
return [name for name, field in self.SCHEMA.items()
if self._is_highlightable(field)]
def _is_highlightable(self, field):
return not isinstance(field, whoosh.fields.DATETIME) and field.stored
def _is_desc(self, order):
return (order.lower()==DESC)
def _process_results(self,
page,
fields,
highlight_fields,
search_parameters=None):
# It's important to grab the hits first before slicing. Otherwise, this
# can cause pagination failures.
"""
:type fields: iterator
:type page: ResultsPage
"""
results = QueryResult()
results.hits = page.total
results.total_page_count = page.pagecount
results.page_number = page.pagenum
results.offset = page.offset
results.facets = self._load_facets(page)
docs = []
highlighting = []
for retrieved_record in page:
result_doc = self._process_record(fields, retrieved_record)
docs.append(result_doc)
result_highlights = self._create_highlights(highlight_fields,
retrieved_record)
highlighting.append(result_highlights)
results.docs = docs
results.highlighting = highlighting
results.debug["search_parameters"] = search_parameters
return results
def _process_record(self, fields, retrieved_record):
result_doc = dict()
#add score field by default
if not fields or SCORE in fields:
score = retrieved_record.score
result_doc[SCORE] = score
if fields:
for field in fields:
if field in retrieved_record:
result_doc[field] = retrieved_record[field]
else:
for key, value in retrieved_record.items():
result_doc[key] = value
for key, value in result_doc.iteritems():
result_doc[key] = self._from_whoosh_format(value)
return result_doc
def _load_facets(self, page):
"""This method can be also used by unit-tests"""
non_paged_results = page.results
facet_names = non_paged_results.facet_names()
if not facet_names:
return None
facets_result = dict()
for name in facet_names:
facets_result[name] = non_paged_results.groups(name)
return facets_result
def _make_dir_if_not_exists(self):
if not os.path.exists(self.index_dir):
os.mkdir(self.index_dir)
if not os.access(self.index_dir, os.W_OK):
raise TracError(
"The path to Whoosh index '%s' is not writable for the\
current user."
% self.index_dir)
def _create_highlights(self, fields, record):
result_highlights = dict()
fragmenter = whoosh.highlight.ContextFragmenter(
self.max_fragment_size,
self.fragment_surround,
)
highlighter = whoosh.highlight.Highlighter(
formatter=WhooshEmFormatter(),
fragmenter=fragmenter)
for field in fields:
if field in record:
highlighted = highlighter.highlight_hit(record, field)
else:
highlighted = ''
result_highlights[field] = highlighted
return result_highlights
class WhooshEmFormatter(whoosh.highlight.HtmlFormatter):
template = '<em>%(t)s</em>'
class AdvancedFilterCollector(FilterCollector):
"""An advanced filter collector, accepting a callback function that
will be called for each document to determine whether it should be
filtered out or not.
Please note that it can be slow. Very slow.
"""
def __init__(self, child, allow, restrict, filter_func=None):
FilterCollector.__init__(self, child, allow, restrict)
self.filter_func = filter_func
def collect_matches(self):
child = self.child
_allow = self._allow
_restrict = self._restrict
if _allow is not None or _restrict is not None:
filtered_count = self.filtered_count
for sub_docnum in child.matches():
global_docnum = self.offset + sub_docnum
if ((_allow is not None and global_docnum not in _allow)
or (_restrict is not None and global_docnum in _restrict)):
filtered_count += 1
continue
if self.filter_func:
doc = self.subsearcher.stored_fields(sub_docnum)
if not self.filter_func(doc):
filtered_count += 1
continue
child.collect(sub_docnum)
# pylint: disable=attribute-defined-outside-init
self.filtered_count = filtered_count
else:
# If there was no allow or restrict set, don't do anything special,
# just forward the call to the child collector
child.collect_matches()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/real_index_view.py | bloodhound_search/bhsearch/tests/real_index_view.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
from trac.test import EnvironmentStub, Mock, MockPerm
from trac.web import Href, arg_list_to_args
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.web_ui import RequestParameters
from bhsearch.whoosh_backend import WhooshBackend
from whoosh import query
class RealIndexTestCase(BaseBloodhoundSearchTest):
"""
This test case is not supposed to be run from CI tool.
The purpose of the class is to work with real Bloodhound Search Index and
should be used for debugging purposes only
"""
def setUp(self):
self.env = EnvironmentStub(enable=['bhsearch.*'])
current_current_dir = os.getcwd()
real_env_path = os.path.join(
current_current_dir,
"../../../installer/bloodhound/environments/main")
self.env.path = real_env_path
self.whoosh_backend = WhooshBackend(self.env)
self.req = Mock(
perm=MockPerm(),
chrome={'logo': {}},
href=Href("/main"),
args=arg_list_to_args([]),
)
def test_read_all(self):
result = self.whoosh_backend.query(
query.Every()
)
self.print_result(result)
result = self.whoosh_backend.query(
query.Every()
)
self.print_result(result)
self.assertLessEqual(1, result.hits)
def test_read_with_type_facet(self):
result = self.whoosh_backend.query(
query.Every()
)
self.print_result(result)
result = self.whoosh_backend.query(
query.Every(),
facets=["type"]
)
self.print_result(result)
self.assertLessEqual(1, result.hits)
def test_read_from_search_module(self):
self.req.args[RequestParameters.QUERY] = "*"
self.process_request()
def suite():
pass
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/api.py | bloodhound_search/bhsearch/tests/api.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import shutil
from bhsearch.api import BloodhoundSearchApi, ASC, SortInstruction, IIndexParticipant, IndexFields
from bhsearch.query_parser import DefaultQueryParser
from bhsearch.search_resources.base import BaseIndexer
from bhsearch.search_resources.ticket_search import TicketSearchParticipant
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
from trac.core import implements, ComponentMeta
class ApiQueryWithWhooshTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(ApiQueryWithWhooshTestCase, self).setUp(create_req=True)
WhooshBackend(self.env).recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
self.ticket_participant = TicketSearchParticipant(self.env)
self.query_parser = DefaultQueryParser(self.env)
def tearDown(self):
shutil.rmtree(self.env.path)
self.env.reset_db()
def test_can_search_free_description(self):
#arrange
self.insert_ticket("dummy summary", description="aaa keyword bla")
#act
results = self.search_api.query("keyword")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
def test_can_query_free_summary(self):
#arrange
self.insert_ticket("summary1 keyword")
#act
results = self.search_api.query("keyword")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
def test_can_query_strict_summary(self):
#arrange
self.insert_ticket("summary1 keyword")
self.insert_ticket("summary2", description = "bla keyword")
#act
results = self.search_api.query("summary:keyword")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
def test_that_summary_hit_is_higher_than_description(self):
#arrange
self.insert_ticket("summary1 keyword")
self.insert_ticket("summary2", description = "bla keyword")
#act
results = self.search_api.query("keyword")
self.print_result(results)
#assert
self.assertEqual(2, results.hits)
docs = results.docs
self.assertEqual("summary1 keyword", docs[0]["summary"])
self.assertEqual("summary2", docs[1]["summary"])
def test_other_conditions_applied(self):
#arrange
self.insert_ticket("summary1 keyword", status="closed")
self.insert_ticket("summary2", description = "bla keyword")
self.insert_ticket("summary3", status="closed")
#act
results = self.search_api.query("keyword status:closed")
self.print_result(results)
#assert
self.assertEqual(1, results.hits)
docs = results.docs
self.assertEqual("summary1 keyword", docs[0]["summary"])
def test_that_filter_queries_applied(self):
#arrange
self.insert_ticket("t1", status="closed", component = "c1")
self.insert_ticket("t2", status="closed", component = "c1")
self.insert_ticket("t3", status="closed",
component = "NotInFilterCriteria")
#act
results = self.search_api.query(
"*",
filter= ['status:"closed"', 'component:"c1"'],
sort= [SortInstruction("id", ASC)]
)
self.print_result(results)
#assert
self.assertEqual(2, results.hits)
docs = results.docs
self.assertEqual("t1", docs[0]["summary"])
self.assertEqual("t2", docs[1]["summary"])
def test_that_upgrading_environment_adds_documents_to_index(self):
self.insert_ticket("t1")
self.insert_ticket("t2")
self.search_api.upgrade_environment(self.env.db_transaction)
results = self.search_api.query("type:ticket")
self.assertEqual(2, results.hits)
def test_can_index_wiki_with_same_id_from_different_products(self):
with self.product('p1'):
self.insert_wiki('title', 'content')
with self.product('p2'):
self.insert_wiki('title', 'content 2')
results = self.search_api.query("type:wiki")
self.assertEqual(results.hits, 2)
def test_upgrade_index_with_no_product(self):
"""See #773"""
class NoProductIndexer(BaseIndexer):
implements(IIndexParticipant)
def get_entries_for_index(self):
yield {
IndexFields.TYPE: 'noproduct',
IndexFields.ID: '1'
}
self.search_api.rebuild_index()
self.unregister(NoProductIndexer)
@staticmethod
def unregister(component):
ComponentMeta._components.remove(component)
for interface in component.__dict__.get('_implements', ()):
ComponentMeta._registry.get(interface).remove(component)
#TODO: check this later
# @unittest.skip("Check with Whoosh community")
# def test_can_search_id_and_summary(self):
# #arrange
# self.insert_ticket("summary1")
# self.insert_ticket("summary2 1")
# #act
# results = self.search_api.query("1")
# self.print_result(results)
# #assert
# self.assertEqual(2, results.hits)
# docs = results.docs
# self.assertEqual("summary1", docs[0]["summary"])
def suite():
return unittest.makeSuite(ApiQueryWithWhooshTestCase, 'test')
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/security.py | bloodhound_search/bhsearch/tests/security.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
This module contains tests of search security using the actual permission
system backend.
"""
import contextlib
import os
from bhsearch.security import SecurityFilter
try:
import configobj
except ImportError:
configobj = None
from trac.perm import (
DefaultPermissionPolicy, PermissionCache, PermissionSystem
)
from bhsearch.api import BloodhoundSearchApi
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
from multiproduct.api import MultiProductSystem, ProductEnvironment
# TODO: Convince trac to register modules without these imports
from trac.wiki import web_ui
from bhsearch import security
class SecurityTest(BaseBloodhoundSearchTest):
def setUp(self, enabled=[]):
super(SecurityTest, self).setUp(
enabled=enabled + ['trac.*', 'trac.wiki.*',
'bhsearch.*', 'multiproduct.*'],
create_req=True,
enable_security=True,
)
self.env.parent = None
self.product_envs = []
self.req.perm = PermissionCache(self.env, 'x')
self._setup_multiproduct()
self._disable_trac_caches()
self._create_whoosh_index()
self.search_api = BloodhoundSearchApi(self.env)
self._add_products('p1', 'p2')
def _setup_multiproduct(self):
try:
MultiProductSystem(self.env)\
.upgrade_environment(self.env.db_transaction)
except self.env.db_exc.OperationalError:
# table remains but content is deleted
self._add_products('@')
self.env.enable_multiproduct_schema()
def _disable_trac_caches(self):
DefaultPermissionPolicy.CACHE_EXPIRY = 0
self._clear_permission_caches()
def _create_whoosh_index(self):
WhooshBackend(self.env).recreate_index()
def _add_products(self, *products, **kwargs):
owner = kwargs.pop('owner', '')
with self.env.db_direct_transaction as db:
for product in products:
db("INSERT INTO bloodhound_product (prefix, owner) "
" VALUES ('%s', '%s')" % (product, owner))
product = ProductEnvironment(self.env, product)
self.product_envs.append(product)
@contextlib.contextmanager
def product(self, prefix=''):
global_env = self.env
self.env = ProductEnvironment(global_env, prefix)
yield
self.env = global_env
def _add_permission(self, username='', permission='', product=''):
with self.env.db_direct_transaction as db:
db("INSERT INTO permission (username, action, product)"
"VALUES ('%s', '%s', '%s')" %
(username, permission, product))
self._clear_permission_caches()
def _clear_permission_caches(self):
for env in [self.env] + self.product_envs:
del PermissionSystem(env).store._all_permissions
class MultiProductSecurityTestCase(SecurityTest):
def test_applies_security(self):
self.insert_ticket('ticket 1')
with self.product('p1'):
self.insert_wiki('page 1', 'content')
self.insert_ticket('ticket 2')
with self.product('p2'):
self.insert_wiki('page 2', 'content 2')
self.insert_ticket('ticket 3')
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(0, results.hits)
self._add_permission('x', 'WIKI_VIEW')
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(0, results.hits)
self._add_permission('x', 'WIKI_VIEW', 'p1')
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(1, results.hits)
self._add_permission('x', 'WIKI_VIEW', 'p2')
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(2, results.hits)
self._add_permission('x', 'TICKET_VIEW', 'p2')
results = self.search_api.query("*", context=self.context)
self.assertEqual(3, results.hits)
self._add_permission('x', 'TICKET_VIEW', 'p1')
results = self.search_api.query("*", context=self.context)
self.assertEqual(4, results.hits)
self._add_permission('x', 'TICKET_VIEW')
results = self.search_api.query("*", context=self.context)
self.assertEqual(5, results.hits)
def test_admin_has_access(self):
with self.product('p1'):
self.insert_wiki('page 1', 'content')
self._add_permission('x', 'TRAC_ADMIN')
results = self.search_api.query("*", context=self.context)
self.assertEqual(1, results.hits)
def test_admin_granted_in_product_should_not_have_access(self):
with self.product('p1'):
self.insert_wiki('page 1', 'content')
self._add_permission('x', 'TRAC_ADMIN', 'p1')
results = self.search_api.query("*", context=self.context)
self.assertEqual(1, results.hits)
def test_product_owner_has_access(self):
self._add_products('p3', owner='x')
with self.product('p3'):
self.insert_ticket("ticket")
results = self.search_api.query("*", context=self.context)
self.assertEqual(1, results.hits)
def test_user_with_no_permissions(self):
with self.product('p1'):
self.insert_wiki('page 1', 'content')
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(0, results.hits)
def test_adding_security_filters_retains_existing_filters(self):
with self.product('p1'):
self.insert_ticket("ticket 1")
self.insert_ticket("ticket 2", status="closed")
with self.product('p2'):
self.insert_ticket("ticket 3", status="closed")
self._add_permission('x', 'TICKET_VIEW', 'p1')
self._add_permission('x', 'TICKET_VIEW', 'p2')
results = self.search_api.query(
"*",
filter=["status:closed"],
context=self.context
)
self.assertEqual(2, results.hits)
def test_product_dropdown_with_no_permission(self):
self._add_permission('x', 'SEARCH_VIEW')
data = self.process_request()
product_list = data['search_product_list']
self.assertEqual(2, len(product_list))
def test_product_dropdown_with_trac_admin_permission(self):
self._add_permission('x', 'SEARCH_VIEW')
self._add_permission('x', 'TRAC_ADMIN')
data = self.process_request()
product_list = data['search_product_list']
self.assertEqual(5, len(product_list))
def test_product_dropdown_with_product_view_permissions(self):
self._add_permission('x', 'SEARCH_VIEW')
self._add_permission('x', 'PRODUCT_VIEW', '@')
data = self.process_request()
product_list = data['search_product_list']
self.assertEqual(3, len(product_list))
def test_check_permission_is_called_with_advanced_security(self):
self.env.config.set('bhsearch', 'advanced_security', "True")
self.insert_ticket('ticket 1')
with self.product('p1'):
self.insert_wiki('page 1', 'content')
self.insert_ticket('ticket 2')
with self.product('p2'):
self.insert_wiki('page 2', 'content 2')
self.insert_ticket('ticket 3')
self._add_permission('x', 'TRAC_ADMIN')
calls = []
def check_permission(self, doc, context):
# pylint: disable=unused-argument
calls.append((doc, context))
return True
security.SecurityPreprocessor.check_permission = check_permission
results = self.search_api.query(
"*",
context=self.context
)
self.assertEqual(5, results.hits)
self.assertEqual(5, len(calls))
def test_advanced_security_overrides_normal_permissions(self):
self.env.config.set('bhsearch', 'advanced_security', "True")
self.insert_ticket('ticket 1')
with self.product('p1'):
self.insert_ticket('ticket 2')
self._add_permission('x', 'TRAC_ADMIN')
security.SecurityPreprocessor.check_permission = \
lambda x, doc, z: doc.get('product', None) == 'p1'
results = self.search_api.query(
"*",
context=self.context
)
self.assertEqual(1, results.hits)
class AuthzSecurityTestCase(SecurityTest):
def setUp(self, enabled=()):
SecurityTest.setUp(self, enabled=['tracopt.perm.authz_policy.*'])
self.authz_config = os.path.join(self.env.path, 'authz.conf')
self.env.config['authz_policy'].set('authz_file', self.authz_config)
self.env.config['trac'].set('permission_policies',
'AuthzPolicy,DefaultPermissionPolicy,'
'LegacyAttachmentPolicy')
# Create some dummy objects
self.insert_ticket('ticket 1')
self.insert_ticket('ticket 2')
self.insert_wiki('page 1', 'content')
with self.product('p1'):
self.insert_ticket('ticket 1 in p1')
self.insert_wiki('page 1', 'content')
def write_authz_config(self, content):
with open(self.authz_config, 'w') as authz_config:
authz_config.write(content)
def test_authz_permissions(self):
self._add_permission('x', 'WIKI_VIEW')
self.write_authz_config("""
[*]
* = TICKET_VIEW, !WIKI_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(3, results.hits)
results = self.search_api.query("type:wiki", context=self.context)
self.assertEqual(0, results.hits)
def test_granular_permissions(self):
self.write_authz_config("""
[ticket:1]
* = TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(2, results.hits)
self.assertEqual(u'1', results.docs[0]['id'])
def test_deny_overrides_default_permissions(self):
self._add_permission('x', 'TICKET_VIEW')
self.write_authz_config("""
[*]
x = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(0, results.hits)
def test_includes_wildcard_rows_for_registered_users(self):
self.write_authz_config("""
[*]
* = TICKET_VIEW
[ticket:1]
* = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
def test_includes_wildcard_rows_for_anonymous_users(self):
self.req.authname = 'anonymous'
self.write_authz_config("""
[*]
* = TICKET_VIEW
[ticket:1]
* = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
def test_includes_authenticated_rows_for_registered_users(self):
self.write_authz_config("""
[*]
* = TICKET_VIEW
[ticket:1]
authenticated = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
def test_includes_named_rows_for_registered_users(self):
self.write_authz_config("""
[*]
* = TICKET_VIEW
[ticket:1]
x = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
def test_includes_named_rows_for_anonymous_users(self):
self.req.authname = 'anonymous'
self.write_authz_config("""
[*]
* = TICKET_VIEW
[ticket:1]
anonymous = !TICKET_VIEW
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
def test_understands_groups(self):
self.write_authz_config("""
[groups]
admins = x
[*]
@admins = TICKET_VIEW
[ticket:1]
* = !TRAC_ADMIN
""")
results = self.search_api.query("type:ticket", context=self.context)
self.assertEqual(1, results.hits)
class SecurityFilterTests(unittest.TestCase):
def test_hash(self):
sf = SecurityFilter()
hash(sf)
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(MultiProductSecurityTestCase))
if configobj:
suite.addTest(unittest.makeSuite(AuthzSecurityTestCase))
suite.addTest(unittest.makeSuite(SecurityFilterTests))
return suite
if __name__ == '__main__':
unittest.main(defaultTest="suite")
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/web_ui.py | bloodhound_search/bhsearch/tests/web_ui.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from urllib import urlencode, unquote, unquote_plus
from trac.core import TracError
from trac.search.web_ui import SearchModule as TracSearchModule
from trac.test import Mock, MockPerm
from trac.util import format_datetime
from trac.util.datefmt import FixedOffset
from trac.web import Href, RequestDone, arg_list_to_args, parse_arg_list
from bhsearch import web_ui
from bhsearch.api import ASC, DESC, SortInstruction
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.web_ui import BloodhoundSearchModule, RequestParameters
from bhsearch.whoosh_backend import WhooshBackend
BASE_PATH = "/main/"
BHSEARCH_URL = BASE_PATH + "bhsearch"
DEFAULT_DOCS_PER_PAGE = 10
class WebUiTestCaseWithWhoosh(BaseBloodhoundSearchTest):
def setUp(self):
super(WebUiTestCaseWithWhoosh, self).setUp(
create_req=True,
)
self.req.redirect = self.redirect
whoosh_backend = WhooshBackend(self.env)
whoosh_backend.recreate_index()
self.req.redirect = self.redirect
self.redirect_url = None
self.redirect_permanent = None
self.old_product_environment = web_ui.ProductEnvironment
self._inject_mocked_product_environment()
def _inject_mocked_product_environment(self):
class MockProductEnvironment(object):
def __init__(self, env, product):
# pylint: disable=unused-argument
self.product = product
def href(self, *args):
return ('/main/products/%s/' % self.product) + '/'.join(args)
def abs_href(self, *args):
return 'http://example.org' + self.href(*args)
from multiproduct.env import ProductEnvironment
resolve_href = ProductEnvironment.resolve_href
web_ui.ProductEnvironment = MockProductEnvironment
def tearDown(self):
web_ui.ProductEnvironment = self.old_product_environment
def redirect(self, url, permanent=False):
self.redirect_url = url
self.redirect_permanent = permanent
raise RequestDone
def test_can_process_empty_request(self):
data = self.process_request()
self.assertEqual("", data["query"])
def test_can_process_query_empty_data(self):
self.req.args[RequestParameters.QUERY] = "bla"
data = self.process_request()
self.assertEqual("bla", data["query"])
self.assertEqual([], data["results"].items)
def test_can_process_first_page(self):
self._insert_tickets(5)
self.req.args[RequestParameters.QUERY] = "summary:test"
data = self.process_request()
self.assertEqual("summary:test", data["query"])
self.assertEqual(5, len(data["results"].items))
def test_can_return_utc_time(self):
#arrange
ticket = self.insert_ticket("bla")
ticket_time = ticket.time_changed
#act
self.req.args[RequestParameters.QUERY] = "*:*"
data = self.process_request()
result_items = data["results"].items
#assert
self.assertEqual(1, len(result_items))
result_datetime = result_items[0]["date"]
self.env.log.debug(
"Ticket time: %s, Returned time: %s",
ticket_time,
result_datetime)
self.assertEqual(format_datetime(ticket_time), result_items[0]["date"])
def test_can_return_user_time(self):
#arrange
ticket = self.insert_ticket("bla")
ticket_time = ticket.time_changed
#act
tzinfo = FixedOffset(60, 'GMT +1:00')
self.req.tz = tzinfo
self.req.args[RequestParameters.QUERY] = "*:*"
data = self.process_request()
result_items = data["results"].items
#asset
self.assertEqual(1, len(result_items))
expected_datetime = format_datetime(ticket_time, tzinfo=tzinfo)
result_datetime = result_items[0]["date"]
self.env.log.debug(
"Ticket time: %s, Formatted time: %s ,Returned time: %s",
ticket_time, expected_datetime, result_datetime)
self.assertEqual(expected_datetime, result_datetime)
def test_ticket_href(self):
self._insert_tickets(1)
self.req.args[RequestParameters.QUERY] = "*:*"
data = self.process_request()
docs = data["results"].items
self.assertEqual(1, len(docs))
self.assertEqual("/main/ticket/1", docs[0]["href"])
def test_product_ticket_href(self):
with self.product('xxx'):
self._insert_tickets(1)
self.req.args[RequestParameters.QUERY] = "*:*"
data = self.process_request()
docs = data["results"].items
self.assertEqual(1, len(docs))
self.assertEqual("/main/products/xxx/ticket/1", docs[0]["href"])
def test_page_href(self):
self._insert_tickets(DEFAULT_DOCS_PER_PAGE+1)
self.req.args[RequestParameters.QUERY] = "*:*"
data = self.process_request()
shown_pages = data["results"].shown_pages
second_page_href = shown_pages[1]["href"]
self.assertIn("page=2", second_page_href)
self.assertIn("q=*%3A*", second_page_href)
def test_can_apply_type_parameter(self):
#arrange
self.insert_ticket("summary1 keyword", status="closed")
self.insert_ticket("summary2 keyword", status="new")
self.insert_wiki("dummyTitle", "Some text")
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.TYPE] = "ticket"
#act
data = self.process_request()
#assert
extra_search_options = dict(data["extra_search_fields"])
self.assertEqual("ticket", extra_search_options['type'])
def test_type_parameter_in_links(self):
self._insert_tickets(12)
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.PAGELEN] = "4"
self.req.args[RequestParameters.PAGE] = "2"
data = self.process_request()
results = data["results"]
docs = results.items
self.assertEquals(4, len(docs))
next_chrome_link = self.req.chrome['links']['next'][0]["href"]
self.assertIn('type=ticket', next_chrome_link)
self.assertIn('page=3', next_chrome_link)
prev_chrome_link = self.req.chrome['links']['prev'][0]["href"]
self.assertIn('type=ticket', prev_chrome_link)
self.assertIn('page=1', prev_chrome_link)
self.assertIn('type=ticket', data["page_href"])
for page in results.shown_pages:
self.assertIn('type=ticket', page["href"])
def test_that_type_facet_is_in_default_search(self):
#arrange
self._insert_tickets(2)
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
self.assertEquals(1, len(data["facet_counts"]))
def test_can_return_facets_counts_for_tickets(self):
#arrange
self.insert_ticket("T1", status="new", milestone="m1")
self.insert_ticket("T2", status="closed")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
facet_counts = dict(data["facet_counts"])
status_counts = facet_counts["status"]
self.assertEquals(1, status_counts["new"]["count"])
self.assertEquals(1, status_counts["closed"]["count"])
def test_can_create_href_for_facet_counts(self):
#arrange
self.insert_ticket("T1", status="new")
self.insert_ticket("T2", status="closed")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
facet_counts = dict(data["facet_counts"])
status_counts = facet_counts["status"]
self.assertEquals(1, status_counts["new"]["count"])
self.assertIn("fq=status%3A%22new%22", status_counts["new"]["href"])
def test_can_handle_none_in_facet_counts(self):
#arrange
self.insert_ticket("T1")
self.insert_ticket("T2")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
facet_counts = dict(data["facet_counts"])
status_counts = facet_counts["status"]
empty_status_count = status_counts[None]
self.assertEquals(2, empty_status_count["count"])
self.assertIn(
'fq=NOT+(status:*)',
unquote(empty_status_count["href"]))
def test_can_return_empty_facets_result_for_wiki_pages(self):
#arrange
self.insert_wiki("W1", "Some text")
#act
self.req.args[RequestParameters.TYPE] = "wiki"
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
facet_counts = data["facet_counts"]
self.assertEquals([], facet_counts)
def test_can_accept_multiple_filter_query_parameters(self):
#arrange
self.insert_ticket("T1", component="c1", status="new")
self.insert_ticket("T2", component="c1", status="new")
self.insert_ticket("T3",)
self._insert_wiki_pages(2)
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.FILTER_QUERY] = [
'component:"c1"', 'status:"new"']
data = self.process_request()
#assert
page_href = data["page_href"]
self.assertIn(urlencode({'fq': 'component:"c1"'}), page_href)
self.assertIn(urlencode({'fq': 'status:"new"'}), page_href)
docs = data["results"].items
self.assertEqual(2, len(docs))
def test_can_handle_empty_facet_result(self):
#arrange
self.insert_ticket("T1", component="c1", status="new")
self.insert_ticket("T2", component="c1", status="new")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.FILTER_QUERY] = ['component:"c1"']
data = self.process_request()
#assert
facet_counts = dict(data["facet_counts"])
milestone_facet_count = facet_counts["milestone"]
self.env.log.debug(unquote(milestone_facet_count[None]["href"]))
def test_can_handle_multiple_same(self):
#arrange
self.insert_ticket("T1", component="c1", status="new")
self.insert_ticket("T2", component="c1", status="new")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.FILTER_QUERY] = ['component:"c1"']
data = self.process_request()
#assert
facet_counts = dict(data["facet_counts"])
component_facet_count = facet_counts["component"]
c1_href = component_facet_count["c1"]["href"]
self.env.log.debug(unquote(c1_href))
self.assertEquals(
1,
self._count_parameter_in_url(c1_href, "fq", 'component:"c1"'))
def test_can_return_current_filter_queries(self):
#arrange
self.insert_ticket("T1", component="c1", status="new")
self.insert_ticket("T2", component="c1", status="new")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.FILTER_QUERY] = [
'component:"c1"',
'status:"new"']
data = self.process_request()
#assert
current_filter_queries = data["active_filter_queries"]
self.assertEquals(3, len(current_filter_queries))
type_filter = current_filter_queries[0]
self.assertEquals('Ticket', type_filter["label"])
self.assertNotIn("type=", type_filter["href"])
self.assertNotIn('fq=', unquote(type_filter["href"]))
component_filter = current_filter_queries[1]
self.assertEquals('component:"c1"', component_filter["label"])
self.assertIn('type=ticket', component_filter["href"])
self.assertNotIn('fq=component:"c1"',
unquote(component_filter["href"]))
self.assertIn('fq=status:"new"', unquote(component_filter["href"]))
status_filter = current_filter_queries[2]
self.assertEquals('status:"new"', status_filter["label"])
self.assertIn('type=ticket', status_filter["href"])
self.assertIn('fq=component:"c1"', unquote(status_filter["href"]))
self.assertNotIn('fq=status:"new"', unquote(status_filter["href"]))
def test_can_return_missing_milestone(self):
#arrange
self.insert_ticket("T1", component="c1", status="new")
self.insert_ticket("T2", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.FILTER_QUERY] = ["NOT (milestone:*)"]
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
items = data["results"].items
self.assertEquals(1, len(items))
def test_can_return_no_results_for_missing_milestone(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
self.insert_ticket("T2", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.FILTER_QUERY] = ["NOT (milestone:*)"]
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
items = data["results"].items
self.assertEquals(0, len(items))
def test_that_type_facet_has_href_to_type(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
ticket_facet_href = dict(data["facet_counts"])["type"]["ticket"]["href"]
ticket_facet_href = unquote(ticket_facet_href)
self.assertIn("type=ticket", ticket_facet_href)
self.assertNotIn("fq=", ticket_facet_href)
def test_that_there_is_no_quick_jump_on_ordinary_query(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
self.assertNotIn("quickjump", data)
def test_can_redirect_on_ticket_id_query(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "#1"
self.assertRaises(RequestDone, self.process_request)
#assert
self.assertEqual('/main/ticket/1', self.redirect_url)
def test_can_return_quick_jump_data_on_noquickjump(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "#1"
self.req.args[RequestParameters.NO_QUICK_JUMP] = "1"
data = self.process_request()
#assert
quick_jump_data = data["quickjump"]
self.assertEqual('T1 (new)', quick_jump_data["description"])
self.assertEqual('/main/ticket/1', quick_jump_data["href"])
def test_that_ticket_search_can_return_in_grid(self):
#arrange
self.env.config.set(
'bhsearch',
'ticket_is_grid_view_default',
'True')
self.env.config.set(
'bhsearch',
'ticket_default_grid_fields',
'id,status,milestone,component')
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.VIEW] = "grid"
data = self.process_request()
#assert
grid_data = data["headers"]
self.assertIsNotNone(grid_data)
fields = [column["name"] for column in grid_data]
self.assertEquals(["id", "status", "milestone", "component"], fields)
def test_that_grid_is_switched_off_by_default(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
self.assertNotIn("headers", data)
self.assertNotIn("view", data)
def test_that_grid_is_switched_off_by_default_for_ticket(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.TYPE] = "ticket"
data = self.process_request()
#assert
self.assertNotIn("headers", data)
self.assertNotIn("view", data)
def test_can_returns_all_views(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
all_views = data["all_views"]
free_view = all_views[0]
self.assertTrue(free_view["is_active"])
self.assertNotIn("view=", free_view["href"])
grid = all_views[1]
self.assertFalse(grid["is_active"])
self.assertIn("view=grid", grid["href"])
def test_that_active_view_is_not_set_if_not_requested(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
self.assertNotIn("active_view", data)
def test_that_active_view_is_set_if_requested(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.VIEW] = "grid"
data = self.process_request()
#assert
extra_search_options = dict(data["extra_search_fields"])
self.assertEqual("grid", extra_search_options["view"])
def test_can_apply_sorting(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
self.insert_ticket("T2", component="c1", status="new", milestone="B")
self.insert_ticket("T3", component="c3", status="new", milestone="C")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.SORT] = "component, milestone desc"
data = self.process_request()
#assert
api_sort = data["debug"]["api_parameters"]["sort"]
self.assertEqual(
[
SortInstruction("component", ASC),
SortInstruction("milestone", DESC),
],
api_sort)
ids = [item["summary"] for item in data["results"].items]
self.assertEqual(["T2", "T1", "T3"], ids)
def test_that_title_is_set_for_free_text_view(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
data = self.process_request()
#assert
self.assertIn("title", data["results"].items[0])
def test_that_grid_header_has_correct_sort_when_default_sorting(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.VIEW] = "grid"
data = self.process_request()
#assert
headers = data["headers"]
id_header = self._find_header(headers, "id")
self.assertIn("sort=id+asc", id_header["href"])
self.assertEquals(None, id_header["sort"])
time_header = self._find_header(headers, "time")
self.assertIn("sort=time+asc", time_header["href"])
self.assertEquals(None, time_header["sort"])
def test_that_grid_header_has_correct_sort_if_acs_sorting(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.QUERY] = "*"
self.req.args[RequestParameters.VIEW] = "grid"
self.req.args[RequestParameters.SORT] = "id"
data = self.process_request()
#assert
headers = data["headers"]
id_header = self._find_header(headers, "id")
self.assertIn("sort=id+desc", id_header["href"])
self.assertEquals("asc", id_header["sort"])
def test_that_active_sort_is_set(self):
#arrange
self.insert_ticket("T1", component="c1", status="new", milestone="A")
#act
self.req.args[RequestParameters.SORT] = "id, time desc"
data = self.process_request()
#assert
extra_search_options = dict(data["extra_search_fields"])
self.assertEqual("id, time desc", extra_search_options["sort"])
def test_that_document_summary_contains_highlighted_search_terms(self):
term = "searchterm"
long_text = "foo " * 200 + term + " bar" * 100
self.insert_wiki("Dummy title", long_text)
self.req.args[RequestParameters.QUERY] = term
data = self.process_request()
content = str(data["results"].items[0]["hilited_content"])
matched_term = '<em>%s</em>' % term
self.assertIn(matched_term, content)
def test_that_only_matched_terms_are_highlighted(self):
term = "search_term"
self.insert_wiki(term, term)
self.req.args[RequestParameters.QUERY] = "name:%s" % term
data = self.process_request()
title = str(data["results"].items[0]["title"])
content = str(data["results"].items[0]["content"])
matched_term = '<em>%s</em>' % term
self.assertIn(matched_term, title)
self.assertNotIn(matched_term, content)
def test_that_matched_terms_in_title_are_highlighted(self):
term = "search_term"
self.insert_wiki(term, 'content')
self.insert_ticket(term)
self.req.args[RequestParameters.QUERY] = term
data = self.process_request()
for row in data["results"].items:
title = str(row["title"])
matched_term = '<em>%s</em>' % term
self.assertIn(matched_term, str(title))
def test_that_html_tags_are_escaped(self):
term = "search_term"
content = '%s <b>%s</b>' % (term, term)
self.insert_wiki(term, content)
self.req.args[RequestParameters.QUERY] = "content:%s" % term
data = self.process_request()
content = str(data["results"].items[0]["hilited_content"])
matched_term = '<em>%s</em>' % term
self.assertIn(matched_term, content)
self.assertNotIn('<b>', content)
self.assertIn('<b>', content)
def test_that_id_is_displayed_even_if_it_doesnt_contain_query_terms(self):
id, term = "1", "search_term"
self.insert_ticket(term, id=id)
self.insert_wiki(id, term)
self.req.args[RequestParameters.QUERY] = term
data = self.process_request()
for row in data["results"].items:
title = row["title"]
self.assertIn(id, str(title))
def test_that_id_is_highlighted_in_title(self):
self.insert_ticket("some summary")
id = "1"
self.req.args[RequestParameters.QUERY] = id
data = self.process_request()
row = data["results"].items[0]
title = row["title"]
self.assertIn('<em>%s</em>' % id, str(title))
def test_that_content_summary_is_trimmed(self):
content = "foo " * 1000
self.insert_wiki("title", content)
data = self.process_request()
for row in data["results"].items:
self.assertLess(len(row['content']), 500)
self.assertLess(len(row['hilited_content']), 500)
def test_compatibility_with_legacy_search(self):
self.env.config.set('bhsearch', 'enable_redirect', "True")
self.req.path_info = '/search'
self.assertRaises(RequestDone, self.process_request)
self.assertIn('/bhsearch', self.redirect_url)
self.assertEqual(self.redirect_permanent, True)
self.req.args['wiki'] = 'on'
self.assertRaises(RequestDone, self.process_request)
redirect_url = unquote_plus(self.redirect_url)
self.assertIn('/bhsearch', redirect_url)
self.assertIn('type=wiki', redirect_url)
self.assertEqual(self.redirect_permanent, True)
self.req.args['ticket'] = 'on'
self.assertRaises(RequestDone, self.process_request)
redirect_url = unquote_plus(self.redirect_url)
self.assertIn('fq=type:(ticket OR wiki)', redirect_url)
self.assertIn('/bhsearch', self.redirect_url)
self.assertEqual(self.redirect_permanent, True)
self.req.args['milestone'] = 'on'
self.assertRaises(RequestDone, self.process_request)
redirect_url = unquote_plus(self.redirect_url)
self.assertIn('fq=type:(ticket OR wiki OR milestone)', redirect_url)
self.assertIn('/bhsearch', self.redirect_url)
self.assertEqual(self.redirect_permanent, True)
self.req.args['changeset'] = 'on'
self.assertRaises(RequestDone, self.process_request)
redirect_url = unquote_plus(self.redirect_url)
self.assertIn(
'fq=type:(ticket OR wiki OR milestone OR changeset)', redirect_url)
self.assertIn('/bhsearch', self.redirect_url)
self.assertEqual(self.redirect_permanent, True)
def test_opensearch_integration(self):
# pylint: disable=unused-variable
self.req.path_info = '/bhsearch/opensearch'
bhsearch = BloodhoundSearchModule(self.env)
url, data, x = bhsearch.process_request(self.req)
self.assertEqual(url, 'opensearch.xml')
def test_returns_correct_handler(self):
bhsearch = BloodhoundSearchModule(self.env)
tracsearch = self.env[TracSearchModule]
class PathInfoSetter(object):
# pylint: disable=incomplete-protocol
def __setitem__(other, key, value):
if key == "PATH_INFO":
self.req.path_info = value
self.req.environ = PathInfoSetter()
self.env.config.set('bhsearch', 'enable_redirect', "True")
self.req.path_info = '/search'
self.assertIs(bhsearch.pre_process_request(self.req, tracsearch),
bhsearch)
self.req.path_info = '/bhsearch'
self.assertIs(bhsearch.pre_process_request(self.req, tracsearch),
bhsearch)
self.env.config.set('bhsearch', 'enable_redirect', "False")
# With redirect disabled, handler should not be changed.
self.req.path_info = '/search'
self.assertIs(bhsearch.pre_process_request(self.req, None),
None)
self.req.path_info = '/bhsearch'
self.assertIs(bhsearch.pre_process_request(self.req, None),
None)
def test_that_correct_search_handle_is_selected_for_quick_search(self):
bhsearch = BloodhoundSearchModule(self.env)
def process_request(path, enable_redirect, is_default):
# pylint: disable=unused-variable
self.req.path_info = path
self.env.config.set('bhsearch', 'enable_redirect',
str(enable_redirect))
self.env.config.set('bhsearch', 'is_default', str(is_default))
template, data, content_type = \
bhsearch.post_process_request(self.req, '', {}, '')
return data
data = process_request('/', enable_redirect=False, is_default=False)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.search())
data = process_request('/', enable_redirect=True, is_default=False)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.bhsearch())
data = process_request('/', enable_redirect=False, is_default=True)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.bhsearch())
data = process_request('/', enable_redirect=True, is_default=True)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.bhsearch())
for is_default in [False, True]:
data = process_request('/search',
enable_redirect=False,
is_default=is_default)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.search())
for is_default in [False, True]:
data = process_request('/search',
enable_redirect=True,
is_default=is_default)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'], self.req.href.bhsearch())
for enable_redirect in [False, True]:
for is_default in [False, True]:
data = process_request('/bhsearch',
enable_redirect=enable_redirect,
is_default=is_default)
self.assertIn('search_handler', data)
self.assertEqual(data['search_handler'],
self.req.href.bhsearch())
def test_that_active_query_is_set(self):
#arrange
self.insert_ticket("Ticket 1", component="c1", status="new")
self.insert_ticket("Ticket 2", component="c1", status="new")
#act
self.req.args[RequestParameters.TYPE] = "ticket"
self.req.args[RequestParameters.QUERY] = "Ticket"
self.req.args[RequestParameters.FILTER_QUERY] = [
'component:"c1"',
'status:"new"']
data = self.process_request()
#assert
active_query = data["active_query"]
self.assertEqual(active_query["label"], '"Ticket"')
self.assertEqual(active_query["query"], "Ticket")
self.assertNotIn("?q=", unquote(active_query["href"]))
self.assertNotIn("&q=", unquote(active_query["href"]))
self.assertIn("fq=", unquote(active_query["href"]))
def test_redirects_if_product_env_is_used_to_access_search(self):
self.env.config.set('bhsearch', 'global_quicksearch', "True")
with self.product('xxx'):
self.assertRaises(RequestDone, self.process_request)
self.assertIn('/bhsearch', self.redirect_url)
self.assertNotIn('/products', self.redirect_url)
self.assertNotIn('product_prefix=xxx', self.redirect_url)
self.assertTrue(self.redirect_permanent)
def test_adds_product_filter_when_global_quicksearch_is_disabled(self):
self.env.config.set('bhsearch', 'global_quicksearch', "false")
with self.product('xxx'):
self.assertRaises(RequestDone, self.process_request)
self.assertIn('/bhsearch', self.redirect_url)
self.assertNotIn('/products', self.redirect_url)
self.assertIn('product_prefix=xxx', self.redirect_url)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | true |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/query_suggestion.py | bloodhound_search/bhsearch/tests/query_suggestion.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from bhsearch.api import BloodhoundSearchApi
from bhsearch.query_suggestion import SuggestionFields
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.web_ui import RequestParameters, RequestContext
from bhsearch.whoosh_backend import WhooshBackend
class QuerySuggestionTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(QuerySuggestionTestCase, self).setUp(create_req=True)
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
def test_fills_suggestion_field(self):
self.insert_ticket("test")
self.insert_milestone("test")
self.insert_wiki("name", "test")
results = self.search_api.query("%s:test" % SuggestionFields.BASKET)
self.assertEqual(results.hits, 3)
def test_provides_suggestions(self):
self.insert_ticket("test")
self.req.args[RequestParameters.QUERY] = "tesk"
data = self.process_request()
self.assertIn(RequestContext.DATA_QUERY_SUGGESTION, data)
suggestion = data[RequestContext.DATA_QUERY_SUGGESTION]
self.assertEqual(suggestion['query'], 'test')
self.assertIn('q=test', suggestion['href'])
def test_provides_suggestions_for_multi_term_queries(self):
self.insert_ticket("another test")
self.req.args[RequestParameters.QUERY] = "another tesk"
data = self.process_request()
suggestion = data[RequestContext.DATA_QUERY_SUGGESTION]
self.assertEqual(suggestion['query'], 'another test')
def test_provides_suggestions_for_queries_with_unknown_words(self):
self.insert_ticket("test")
self.req.args[RequestParameters.QUERY] = "another tesk"
data = self.process_request()
suggestion = data[RequestContext.DATA_QUERY_SUGGESTION]
self.assertEqual(suggestion['query'], 'another test')
def test_suggestion_href_contains_used_filters(self):
self.insert_ticket("test")
self.req.args[RequestParameters.QUERY] = "tesk"
self.req.args[RequestParameters.FILTER_QUERY] = ['filter']
data = self.process_request()
suggestion = data[RequestContext.DATA_QUERY_SUGGESTION]
self.assertIn('fq=filter', suggestion['href'])
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(QuerySuggestionTestCase))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/query_parser.py | bloodhound_search/bhsearch/tests/query_parser.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.test import Mock
from bhsearch.query_parser import DefaultQueryParser
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from whoosh import query
class MetaKeywordsParsingTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(MetaKeywordsParsingTestCase, self).setUp()
self.parser = DefaultQueryParser(self.env)
def test_can_parse_keyword_ticket(self):
parsed_query = self.parser.parse("$ticket")
self.assertEqual(parsed_query, query.Term('type', 'ticket'))
def test_can_parse_NOT_keyword_ticket(self):
parsed_query = self.parser.parse("NOT $ticket")
self.assertEqual(parsed_query,
query.Not(
query.Term('type', 'ticket')))
def test_can_parse_keyword_wiki(self):
parsed_query = self.parser.parse("$wiki")
self.assertEqual(parsed_query, query.Term('type', 'wiki'))
def test_can_parse_keyword_resolved(self):
parsed_query = self.parser.parse("$resolved")
self.assertEqual(parsed_query,
query.Or([query.Term('status', 'resolved'),
query.Term('status', 'closed')]))
def test_can_parse_meta_keywords_that_resolve_to_meta_keywords(self):
parsed_query = self.parser.parse("$unresolved")
self.assertEqual(parsed_query,
query.Not(
query.Or([query.Term('status', 'resolved'),
query.Term('status', 'closed')])))
def test_can_parse_complex_query(self):
parsed_query = self.parser.parse("content:test $ticket $unresolved")
self.assertEqual(parsed_query,
query.And([
query.Term('content', 'test'),
query.Term('type', 'ticket'),
query.Not(
query.Or([query.Term('status', 'resolved'),
query.Term('status', 'closed')])
)
]))
def test_can_parse_keyword_me(self):
context = self._mock_context_with_username('username')
parsed_query = self.parser.parse("author:$me", context)
self.assertEqual(parsed_query, query.Term('author', 'username'))
def test_can_parse_keyword_my(self):
context = self._mock_context_with_username('username')
parsed_query = self.parser.parse("$my", context)
self.assertEqual(parsed_query, query.Term('owner', 'username'))
def _mock_context_with_username(self, username):
context = Mock(
req=Mock(
authname=username
)
)
return context
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(MetaKeywordsParsingTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/index_with_whoosh.py | bloodhound_search/bhsearch/tests/index_with_whoosh.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import shutil
from bhsearch.api import BloodhoundSearchApi
from bhsearch.search_resources.milestone_search import MilestoneIndexer
from bhsearch.search_resources.ticket_search import TicketIndexer
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
class IndexWhooshTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(IndexWhooshTestCase, self).setUp()
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
def tearDown(self):
shutil.rmtree(self.env.path)
self.env.reset_db()
def test_can_index_ticket(self):
ticket = self.create_dummy_ticket()
TicketIndexer(self.env).resource_created(ticket, None)
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(1, results.hits)
def test_that_ticket_indexed_when_inserted_in_db(self):
ticket = self.create_dummy_ticket()
ticket.insert()
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(1, results.hits)
def test_can_reindex_twice(self):
self.insert_ticket("t1")
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#just to test that index was re-created
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.assertEqual(1, results.hits)
def test_can_reindex_tickets(self):
self.insert_ticket("t1")
self.insert_ticket("t2")
self.insert_ticket("t3")
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(3, results.hits)
def test_can_reindex_wiki(self):
self.insert_wiki("page1", "some text")
self.insert_wiki("page2", "some text")
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(2, results.hits)
def test_can_reindex_mixed_types(self):
self.insert_wiki("page1", "some text")
self.insert_ticket("t1")
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(2, results.hits)
def test_can_reindex_milestones(self):
MilestoneIndexer(self.env)
self.insert_milestone("M1")
self.insert_milestone("M2")
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(2, results.hits)
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(IndexWhooshTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/__init__.py | bloodhound_search/bhsearch/tests/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest
from bhsearch.tests import (
api, index_with_whoosh, query_parser, query_suggestion,
search_resources, security, web_ui, whoosh_backend
)
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(api.suite())
test_suite.addTest(index_with_whoosh.suite())
test_suite.addTest(query_parser.suite())
test_suite.addTest(query_suggestion.suite())
test_suite.addTest(search_resources.suite())
test_suite.addTest(web_ui.suite())
test_suite.addTest(whoosh_backend.suite())
test_suite.addTest(security.suite())
return test_suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
else:
test_suite = suite()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/base.py | bloodhound_search/bhsearch/tests/base.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""
Test utils methods
"""
import contextlib
import shutil
import tempfile
from trac.test import EnvironmentStub, Mock, MockPerm
from trac.ticket import Ticket, Milestone
from trac.web import Href, arg_list_to_args
from trac.wiki import WikiPage
from bhsearch.tests import unittest
from bhsearch.web_ui import BloodhoundSearchModule
BASE_PATH = "/main/"
class BaseBloodhoundSearchTest(unittest.TestCase):
def setUp(self, enabled=None, create_req=False, enable_security=False):
if not enabled:
enabled = ['trac.*', 'bhsearch.*']
if not enable_security:
disabled = ['bhsearch.security.*']
else:
disabled = []
self.env = EnvironmentStub(enable=enabled, disable=disabled)
self.env.path = tempfile.mkdtemp('bhsearch-tempenv')
self.env.config.set('bhsearch', 'silence_on_error', "False")
if create_req:
self.req = Mock(
perm=MockPerm(),
chrome={'logo': {}, 'links': {}},
href=Href("/main"),
base_path=BASE_PATH,
path_info='/bhsearch',
args=arg_list_to_args([]),
authname='x',
)
self.context = Mock(req=self.req)
# Test without multiproduct.
if hasattr(self.env, 'parent'):
del self.env.parent
def tearDown(self):
shutil.rmtree(self.env.path)
self.env.reset_db()
def print_result(self, result):
self.env.log.debug("Received result: %s", result.__dict__)
def create_dummy_ticket(self, summary = None):
if not summary:
summary = 'Hello World'
data = {'component': 'foo', 'milestone': 'bar'}
return self.create_ticket(summary, reporter='john', **data)
def create_ticket(self, summary, **kw):
ticket = Ticket(self.env)
ticket["summary"] = summary
for k, v in kw.items():
ticket[k] = v
return ticket
def insert_ticket(self, summary, **kw):
"""Helper for inserting a ticket into the database"""
ticket = self.create_ticket(summary, **kw)
ticket.insert()
return ticket
def create_wiki(self, name, text, **kw):
page = WikiPage(self.env, name)
page.text = text
for k, v in kw.items():
page[k] = v
return page
def insert_wiki(self, name, text = None, **kw):
text = text or "Dummy text"
page = self.create_wiki(name, text, **kw)
return page.save("dummy author", "dummy comment", "::1")
def insert_milestone(self, name, description = None):
milestone = self.create_milestone(
name = name,
description = description)
milestone.insert()
return milestone
def create_milestone(self, name, description = None):
milestone = Milestone(self.env)
milestone.name = name
if description is not None:
milestone.description = description
return milestone
def change_milestone(self, name_to_change, name=None, description=None):
milestone = Milestone(self.env, name_to_change)
if name is not None:
milestone.name = name
if description is not None:
milestone.description = description
milestone.update()
return milestone
def process_request(self):
# pylint: disable=unused-variable
url, data, x = BloodhoundSearchModule(self.env).process_request(
self.req)
self.env.log.debug("Received url: %s data: %s", url, data)
if 'results' in data:
self.env.log.debug("results: %s", data["results"].__dict__)
return data
@contextlib.contextmanager
def product(self, prefix=''):
has_parent = hasattr(self.env, 'parent')
has_product = hasattr(self.env, 'product')
if has_parent:
old_parent = self.env.parent
if has_product:
old_product = self.env.product
self.env.parent = self.env
self.env.product = Mock(prefix=prefix)
yield
if has_parent:
self.env.parent = old_parent
else:
del self.env.parent
if has_product:
self.env.product = old_product
else:
del self.env.product
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/whoosh_backend.py | bloodhound_search/bhsearch/tests/whoosh_backend.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from datetime import datetime
import os
import shutil
import tempfile
from trac.util.datefmt import FixedOffset, utc
from bhsearch.api import ASC, DESC, SCORE, SortInstruction
from bhsearch.query_parser import DefaultQueryParser
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
from whoosh import index, query, sorting
from whoosh.fields import ID, KEYWORD, TEXT, Schema
from whoosh.qparser import MultifieldParser, MultifieldPlugin, PhrasePlugin, \
QueryParser, WhitespacePlugin
class WhooshBackendTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(WhooshBackendTestCase, self).setUp()
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.parser = DefaultQueryParser(self.env)
def test_can_retrieve_docs(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="2", type="ticket"))
result = self.whoosh_backend.query(
query.Every(),
sort = [SortInstruction("id", ASC)],
)
self.print_result(result)
self.assertEqual(2, result.hits)
docs = result.docs
self.assertEqual(
{'id': u'1', 'type': u'ticket', 'unique_id': u'ticket:1',
'score': 0},
docs[0])
self.assertEqual(
{'id': u'2', 'type': u'ticket', 'unique_id': u'ticket:2',
'score': 1},
docs[1])
def test_can_return_all_fields(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
result = self.whoosh_backend.query(query.Every())
self.print_result(result)
docs = result.docs
self.assertEqual(
{'id': u'1', 'type': u'ticket', 'unique_id': u'ticket:1',
"score": 1.0},
docs[0])
def test_can_select_fields(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
result = self.whoosh_backend.query(query.Every(),
fields=("id", "type"))
self.print_result(result)
docs = result.docs
self.assertEqual(
{'id': '1', 'type': 'ticket'},
docs[0])
def test_can_survive_after_restart(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
whoosh_backend2 = WhooshBackend(self.env)
whoosh_backend2.add_doc(dict(id="2", type="ticket"))
result = whoosh_backend2.query(query.Every())
self.assertEqual(2, result.hits)
def test_can_apply_multiple_sort_conditions_asc(self):
self.whoosh_backend.add_doc(dict(id="2", type="ticket2"))
self.whoosh_backend.add_doc(dict(id="3", type="ticket1"))
self.whoosh_backend.add_doc(dict(id="4", type="ticket3"))
self.whoosh_backend.add_doc(dict(id="1", type="ticket1"))
result = self.whoosh_backend.query(
query.Every(),
sort = [SortInstruction("type", ASC), SortInstruction("id", ASC)],
fields=("id", "type"),
)
self.print_result(result)
self.assertEqual([{'type': 'ticket1', 'id': '1'},
{'type': 'ticket1', 'id': '3'},
{'type': 'ticket2', 'id': '2'},
{'type': 'ticket3', 'id': '4'}],
result.docs)
def test_can_apply_multiple_sort_conditions_desc(self):
self.whoosh_backend.add_doc(dict(id="2", type="ticket2"))
self.whoosh_backend.add_doc(dict(id="3", type="ticket1"))
self.whoosh_backend.add_doc(dict(id="4", type="ticket3"))
self.whoosh_backend.add_doc(dict(id="1", type="ticket1"))
result = self.whoosh_backend.query(
query.Every(),
sort = [SortInstruction("type", ASC), SortInstruction("id", DESC)],
fields=("id", "type"),
)
self.print_result(result)
self.assertEqual([{'type': 'ticket1', 'id': '3'},
{'type': 'ticket1', 'id': '1'},
{'type': 'ticket2', 'id': '2'},
{'type': 'ticket3', 'id': '4'}],
result.docs)
def test_can_sort_by_score_and_date(self):
the_first_date = datetime(2012, 12, 1)
the_second_date = datetime(2012, 12, 2)
the_third_date = datetime(2012, 12, 3)
exact_match_string = "texttofind"
not_exact_match_string = "texttofind bla"
self.whoosh_backend.add_doc(dict(
id="1",
type="ticket",
summary=not_exact_match_string,
time=the_first_date,
))
self.whoosh_backend.add_doc(dict(
id="2",
type="ticket",
summary=exact_match_string,
time=the_second_date,
))
self.whoosh_backend.add_doc(dict(
id="3",
type="ticket",
summary=not_exact_match_string,
time=the_third_date,
))
self.whoosh_backend.add_doc(dict(
id="4",
type="ticket",
summary="some text out of search scope",
time=the_third_date,
))
parsed_query = self.parser.parse("summary:texttofind")
result = self.whoosh_backend.query(
parsed_query,
sort = [
SortInstruction(SCORE, ASC),
SortInstruction("time", DESC)
],
)
self.print_result(result)
self.assertEqual(3, result.hits)
docs = result.docs
#must be found first, because the highest score (of exact match)
self.assertEqual("2", docs[0]["id"])
#must be found second, because the time order DESC
self.assertEqual("3", docs[1]["id"])
#must be found third, because the time order DESC
self.assertEqual("1", docs[2]["id"])
def test_can_do_facet_count(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket", product="A"))
self.whoosh_backend.add_doc(dict(id="2", type="ticket", product="B"))
self.whoosh_backend.add_doc(dict(id="3", type="wiki", product="A"))
result = self.whoosh_backend.query(
query.Every(),
sort = [SortInstruction("type", ASC), SortInstruction("id", DESC)],
fields=("id", "type"),
facets= ("type", "product")
)
self.print_result(result)
self.assertEqual(3, result.hits)
facets = result.facets
self.assertEqual({"ticket":2, "wiki":1}, facets["type"])
self.assertEqual({"A":2, "B":1}, facets["product"])
def test_can_do_facet_if_filed_missing_TODO(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="2", type="ticket", status="New"))
result = self.whoosh_backend.query(
query.Every(),
facets= ("type", "status")
)
self.print_result(result)
self.assertEqual(2, result.hits)
facets = result.facets
self.assertEqual({"ticket":2}, facets["type"])
self.assertEqual({None: 1, 'New': 1}, facets["status"])
def test_can_return_empty_result(self):
result = self.whoosh_backend.query(
query.Every(),
sort = [SortInstruction("type", ASC), SortInstruction("id", DESC)],
fields=("id", "type"),
facets= ("type", "product")
)
self.print_result(result)
self.assertEqual(0, result.hits)
def test_can_search_time_with_utc_tzinfo(self):
time = datetime(2012, 12, 13, 11, 8, 34, 711957,
tzinfo=FixedOffset(0, 'UTC'))
self.whoosh_backend.add_doc(dict(id="1", type="ticket", time=time))
result = self.whoosh_backend.query(query.Every())
self.print_result(result)
self.assertEqual(time, result.docs[0]["time"])
def test_can_search_time_without_tzinfo(self):
time = datetime(2012, 12, 13, 11, 8, 34, 711957, tzinfo=None)
self.whoosh_backend.add_doc(dict(id="1", type="ticket", time=time))
result = self.whoosh_backend.query(query.Every())
self.print_result(result)
self.assertEqual(time.replace(tzinfo=utc), result.docs[0]["time"])
def test_can_search_time_with_non_utc_tzinfo(self):
hours = 8
tz_diff = 1
time = datetime(2012, 12, 13, 11, hours, 34, 711957,
tzinfo=FixedOffset(tz_diff, "just_one_timezone"))
self.whoosh_backend.add_doc(dict(id="1", type="ticket", time=time))
result = self.whoosh_backend.query(query.Every())
self.print_result(result)
self.assertEqual(datetime(2012, 12, 13, 11, hours-tz_diff, 34, 711957,
tzinfo=utc), result.docs[0]["time"])
def test_can_apply_filter_and_facet(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="2", type="wiki" ))
result = self.whoosh_backend.query(
query.Every(),
filter=query.Term("type", "ticket"),
facets=["type"]
)
self.print_result(result)
self.assertEqual(1, result.hits)
self.assertEqual("ticket", result.docs[0]["type"])
@unittest.skip("TODO clarify behavior on Whoosh mail list")
def test_can_search_id_and_summary_TODO(self):
#arrange
self.insert_ticket("test x")
self.insert_ticket("test 1")
fieldboosts = dict(
id = 1,
summary = 1,
)
mfp = MultifieldPlugin(list(fieldboosts.keys()),)
pins = [WhitespacePlugin,
PhrasePlugin,
mfp]
parser = QueryParser(None, WhooshBackend.SCHEMA, plugins=pins)
parsed_query = parser.parse("1")
result = self.whoosh_backend.query(parsed_query)
self.print_result(result)
self.assertEqual(2, result.hits)
def test_no_index_error_when_counting_facet_on_missing_field(self):
"""
Whoosh 2.4.1 raises "IndexError: list index out of range"
when search contains facets on field that is missing in at least one
document in the index. The error manifests only when index contains
more than one segment
Introduced workaround should solve this problem.
"""
#add more tickets to make sure we have more than one segment in index
count = 20
for i in range(count):
self.insert_ticket("test %s" % (i))
result = self.whoosh_backend.query(
query.Every(),
facets=["milestone"]
)
self.assertEquals(count, result.hits)
def test_can_query_missing_field_and_type(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="2", type="ticket", milestone="A"))
self.whoosh_backend.add_doc(dict(id="3", type="wiki"))
filter = self.parser.parse_filters(["NOT (milestone:*)", "type:ticket"])
result = self.whoosh_backend.query(
query.Every(),
filter=filter,
)
self.print_result(result)
self.assertEqual(1, result.hits)
self.assertEqual("1", result.docs[0]["id"])
def test_can_query_missing_field(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="2", type="ticket", milestone="A"))
filter = self.parser.parse_filters(["NOT (milestone:*)"])
result = self.whoosh_backend.query(
query.Every(),
filter=filter,
)
self.print_result(result)
self.assertEqual(1, result.hits)
self.assertEqual("1", result.docs[0]["id"])
@unittest.skip("TODO clarify behavior on Whoosh mail list")
def test_can_query_missing_field_and_type_with_no_results(self):
self.whoosh_backend.add_doc(dict(id="1", type="ticket"))
self.whoosh_backend.add_doc(dict(id="3", type="wiki"))
filter = self.parser.parse_filters(["NOT (milestone:*)", "type:ticket"])
result = self.whoosh_backend.query(
query.Every(),
filter=filter,
)
self.print_result(result)
self.assertEqual(0, result.hits)
def test_can_highlight_given_terms(self):
term = 'search_term'
text = "foo foo %s bar bar" % term
self.whoosh_backend.add_doc(dict(id="1", type="ticket", content=text))
self.whoosh_backend.add_doc(dict(id="3", type="wiki", content=text))
search_query = self.parser.parse(term)
result = self.whoosh_backend.query(
search_query,
highlight=True,
highlight_fields=['content', 'summary']
)
self.print_result(result)
self.assertEqual(len(result.highlighting), 2)
for highlight in result.highlighting:
self.assertIn(self._highlighted(term), highlight['content'])
self.assertEquals("", highlight['summary'])
def test_that_highlighting_escapes_html(self):
term = 'search_term'
text = "bla <a href=''>%s bar</a> bla" % term
self.whoosh_backend.add_doc(dict(id="1", type="ticket", content=text))
search_query = self.parser.parse(term)
result = self.whoosh_backend.query(
search_query,
highlight=True,
highlight_fields=['content']
)
self.print_result(result)
self.assertEqual(len(result.highlighting), 1)
highlight = result.highlighting[0]
self.assertEquals(
"bla <a href=''><em>search_term</em> bar</a> bla",
highlight['content'])
def test_highlights_all_text_fields_by_default(self):
term = 'search_term'
text = "foo foo %s bar bar" % term
self.whoosh_backend.add_doc(dict(id="1", type="ticket", content=text))
self.whoosh_backend.add_doc(dict(id="3", type="wiki", content=text))
search_query = self.parser.parse(term)
result = self.whoosh_backend.query(
search_query,
highlight=True,
)
self.print_result(result)
self.assertEqual(len(result.highlighting), 2)
for highlight in result.highlighting:
self.assertIn('content', highlight)
self.assertIn('summary', highlight)
self.assertIn(self._highlighted(term), highlight['content'])
def test_only_highlights_terms_in_fields_that_match_query(self):
term = 'search_term'
self.whoosh_backend.add_doc(dict(id=term, type="wiki", content=term))
self.whoosh_backend.add_doc(dict(id=term, type="ticket", summary=term))
search_query = self.parser.parse('id:%s' % term)
result = self.whoosh_backend.query(
search_query,
highlight=True,
highlight_fields=["id", "content", "summary"]
)
self.print_result(result)
self.assertEqual(len(result.highlighting), 2)
for highlight in result.highlighting:
self.assertIn(self._highlighted(term), highlight['id'])
self.assertNotIn(self._highlighted(term), highlight['summary'])
self.assertNotIn(self._highlighted(term), highlight['content'])
def _highlighted(self, term):
return '<em>%s</em>' % term
class WhooshIndexCreationTests(BaseBloodhoundSearchTest):
def setUp(self):
super(WhooshIndexCreationTests, self).setUp()
self.index_dir = os.path.join(self.env.path, 'whoosh_index')
if not os.path.exists(self.index_dir):
os.mkdir(self.index_dir)
def test_does_not_automatically_create_index(self):
whoosh_backend = WhooshBackend(self.env)
self.assertIs(whoosh_backend.index, None)
self.assertEqual(whoosh_backend.is_index_outdated(), True)
whoosh_backend.recreate_index()
self.assertEqual(whoosh_backend.is_index_outdated(), False)
self.assertIsNot(whoosh_backend.index, None)
def test_detects_that_index_needs_upgrade(self):
wrong_schema = Schema(content=TEXT())
index.create_in(self.index_dir, schema=wrong_schema)
whoosh_backend = WhooshBackend(self.env)
self.assertEqual(whoosh_backend.is_index_outdated(), True)
whoosh_backend.recreate_index()
self.assertEqual(whoosh_backend.is_index_outdated(), False)
class WhooshFunctionalityTestCase(unittest.TestCase):
def setUp(self):
self.index_dir = tempfile.mkdtemp('whoosh_index')
def tearDown(self):
shutil.rmtree(self.index_dir)
def test_groupedby_empty_field(self):
schema = Schema(
unique_id=ID(stored=True, unique=True),
id=ID(stored=True),
type=ID(stored=True),
status=KEYWORD(stored=True),
content=TEXT(stored=True),
)
ix = index.create_in(self.index_dir, schema=schema)
with ix.writer() as w:
w.add_document(unique_id=u"1", type=u"type1")
w.add_document(unique_id=u"2", type=u"type2", status=u"New")
facet_fields = (u"type", u"status" )
groupedby = facet_fields
with ix.searcher() as s:
r = s.search(
query.Every(),
groupedby=groupedby,
maptype=sorting.Count,
)
facets = self._load_facets(r)
self.assertEquals(
{'status': {None: 1, 'New': 1}, 'type': {'type1': 1, 'type2': 1}},
facets)
def _load_facets(self, non_paged_results):
facet_names = non_paged_results.facet_names()
if not facet_names:
return None
facets_result = dict()
for name in facet_names:
facets_result[name] = non_paged_results.groups(name)
return facets_result
def test_can_auto_commit(self):
# pylint: disable=unused-argument
schema = Schema(
unique_id=ID(stored=True, unique=True),
type=ID(stored=True),
)
ix = index.create_in(self.index_dir, schema=schema)
with ix.writer() as w:
w.add_document(unique_id=u"1", type=u"type1")
w.add_document(unique_id=u"2", type=u"type2")
with ix.searcher() as s:
results = s.search(query.Every())
self.assertEquals(2, len(results))
def test_can_auto_cancel(self):
schema = Schema(
unique_id=ID(stored=True, unique=True),
type=ID(stored=True),
)
ix = index.create_in(self.index_dir, schema=schema)
try:
with ix.writer() as w:
w.add_document(unique_id=u"1", type=u"type1")
w.add_document(unique_id=u"2", type=u"type2")
raise Exception("some exception")
except Exception:
pass
with ix.searcher() as s:
results = s.search(query.Every())
self.assertEquals(0, len(results))
def test_handles_stop_words_in_queries(self):
schema = WhooshBackend.SCHEMA
ix = index.create_in(self.index_dir, schema=schema)
with ix.writer() as w:
w.add_document(content=u"A nice sentence with stop words.")
with ix.searcher() as s:
query_text = u"with stop"
# field_names both ignore stop words
q = MultifieldParser(['content', 'summary'],
WhooshBackend.SCHEMA).parse(query_text)
self.assertEqual(unicode(q.simplify(s)),
u'((content:with OR summary:with) AND '
u'(content:stop OR summary:stop))')
self.assertEqual(len(s.search(q)), 1)
# 'content' and 'id' ignores stop words
q = MultifieldParser(['content', 'id'],
WhooshBackend.SCHEMA).parse(query_text)
self.assertEqual(unicode(q.simplify(s)),
u'((content:with OR id:with) AND '
u'(content:stop OR id:stop))')
self.assertEqual(len(s.search(q)), 1)
def test_can_filter_to_no_results(self):
schema = Schema(
id=ID(stored=True),
filter=TEXT(stored=True),
)
ix = index.create_in(self.index_dir, schema=schema)
with ix.writer() as w:
w.add_document(id=u"1", filter=u"f1")
w.add_document(id=u"2", filter=u"f2")
with ix.searcher() as s:
r = s.search(
query.Every(),
filter=QueryParser('', schema).parse(u"filter:other")
)
self.assertEquals(len(r), 0)
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(WhooshBackendTestCase))
test_suite.addTest(unittest.makeSuite(WhooshFunctionalityTestCase))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/ticket_search.py | bloodhound_search/bhsearch/tests/search_resources/ticket_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.ticket.model import Component
from bhsearch.api import BloodhoundSearchApi
from bhsearch.search_resources.ticket_search import TicketIndexer
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
class TicketIndexerTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(TicketIndexerTestCase, self).setUp()
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.ticket_indexer = TicketIndexer(self.env)
self.search_api = BloodhoundSearchApi(self.env)
self.env.config.set('bhsearch', 'silence_on_error', "False")
def tearDown(self):
pass
def test_does_not_raise_exception_by_default(self):
self.env.config.set('bhsearch', 'silence_on_error', "True")
self.ticket_indexer.resource_created(None, None)
def test_raise_exception_if_configured(self):
self.env.config.set('bhsearch', 'silence_on_error', "False")
self.assertRaises(
Exception,
self.ticket_indexer.resource_created,
None)
def test_can_strip_wiki_syntax(self):
#act
self.insert_ticket("T1", description=" = Header")
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(1, results.hits)
self.assertEqual("Header", results.docs[0]["content"])
def test_that_tickets_updated_after_component_renaming(self):
#arrange
INITIAL_COMPONENT = "initial_name"
RENAMED_COMPONENT = "renamed_name"
component = self._insert_component(INITIAL_COMPONENT)
self.insert_ticket("T1", component=INITIAL_COMPONENT)
self.insert_ticket("T2", component=INITIAL_COMPONENT)
#act
component.name = RENAMED_COMPONENT
component.update()
#arrange
results = self.search_api.query("*")
self.print_result(results)
for doc in results.docs:
self.assertEqual(RENAMED_COMPONENT, doc["component"])
def test_that_ticket_updated_after_changing(self):
#arrange
ticket = self.insert_ticket("T1", description="some text")
#act
CHANGED_SUMMARY = "T1 changed"
ticket["summary"] = CHANGED_SUMMARY
ticket.save_changes()
#arrange
results = self.search_api.query("*")
self.print_result(results)
self.assertEqual(CHANGED_SUMMARY, results.docs[0]["summary"])
def test_fills_product_field_if_product_is_set(self):
with self.product('p'):
self.insert_ticket("T1")
results = self.search_api.query("*")
self.assertEqual(results.docs[0]["product"], 'p')
def test_can_work_if_env_does_not_have_product(self):
if 'product' in self.env:
del self.env["product"]
self.insert_ticket("T1")
results = self.search_api.query("*")
self.assertEqual(results.hits, 1)
self.assertNotIn("product", results.docs[0])
def _insert_component(self, name):
component = Component(self.env)
component.name = name
component.insert()
return component
def suite():
return unittest.makeSuite(TicketIndexerTestCase, 'test')
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/milestone_search.py | bloodhound_search/bhsearch/tests/search_resources/milestone_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.ticket import Milestone
from bhsearch.api import BloodhoundSearchApi
from bhsearch.search_resources.milestone_search import (
MilestoneSearchParticipant)
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
class MilestoneIndexerEventsTestCase(BaseBloodhoundSearchTest):
DUMMY_MILESTONE_NAME = "dummyName"
def setUp(self):
super(MilestoneIndexerEventsTestCase, self).setUp()
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
def test_can_index_created_milestone(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME, "dummy text")
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual(self.DUMMY_MILESTONE_NAME, doc["id"])
self.assertEqual("dummy text", doc["content"])
self.assertEqual("milestone", doc["type"])
self.assertNotIn("due", doc )
def test_can_index_minimal_milestone(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME)
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual(self.DUMMY_MILESTONE_NAME, doc["id"])
self.assertNotIn("content", doc)
def test_can_index_renamed_milestone(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME, "dummy text")
self.change_milestone(
self.DUMMY_MILESTONE_NAME,
name="updated name",
description="updated description",
)
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual("updated name", doc["id"])
self.assertEqual("updated description", doc["content"])
def test_can_index_changed_milestone(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME, "dummy text")
self.change_milestone(
self.DUMMY_MILESTONE_NAME,
description="updated description",
)
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual(self.DUMMY_MILESTONE_NAME, doc["id"])
self.assertEqual("updated description", doc["content"])
def test_can_index_delete(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME)
results = self.search_api.query("*")
self.assertEqual(1, results.hits)
#act
Milestone(self.env, self.DUMMY_MILESTONE_NAME).delete()
#assert
results = self.search_api.query("*")
self.print_result(results)
self.assertEqual(0, results.hits)
def test_can_reindex_minimal_milestone(self):
#arrange
self.insert_milestone(self.DUMMY_MILESTONE_NAME)
self.whoosh_backend.recreate_index()
#act
self.search_api.rebuild_index()
#assert
results = self.search_api.query("*:*")
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual(self.DUMMY_MILESTONE_NAME, doc["id"])
self.assertEqual("milestone", doc["type"])
def test_that_tickets_updated_after_milestone_renaming(self):
#asser
INITIAL_MILESTONE = "initial_milestone"
RENAMED_MILESTONE = "renamed_name"
milestone = self.insert_milestone(INITIAL_MILESTONE)
self.insert_ticket("T1", milestone=INITIAL_MILESTONE)
self.insert_ticket("T2", milestone=INITIAL_MILESTONE)
#act
milestone.name = RENAMED_MILESTONE
milestone.update()
#assert
results = self.search_api.query("type:ticket")
self.print_result(results)
self.assertEqual(2, results.hits)
self.assertEqual(RENAMED_MILESTONE, results.docs[0]["milestone"])
self.assertEqual(RENAMED_MILESTONE, results.docs[1]["milestone"])
def test_that_tickets_updated_after_milestone_delete_no_retarget(self):
#asser
INITIAL_MILESTONE = "initial_milestone"
milestone = self.insert_milestone(INITIAL_MILESTONE)
self.insert_ticket("T1", milestone=INITIAL_MILESTONE)
self.insert_ticket("T2", milestone=INITIAL_MILESTONE)
#act
milestone.delete()
#assert
results = self.search_api.query("type:ticket")
self.print_result(results)
self.assertEqual(2, results.hits)
self.assertNotIn("milestone", results.docs[0])
self.assertNotIn("milestone", results.docs[1])
def test_that_tickets_updated_after_milestone_delete_with_retarget(self):
#asser
INITIAL_MILESTONE = "initial_milestone"
RETARGET_MILESTONE = "retarget_milestone"
milestone = self.insert_milestone(INITIAL_MILESTONE)
self.insert_milestone(RETARGET_MILESTONE)
self.insert_ticket("T1", milestone=INITIAL_MILESTONE)
self.insert_ticket("T2", milestone=INITIAL_MILESTONE)
#act
milestone.delete(retarget_to=RETARGET_MILESTONE)
#assert
results = self.search_api.query("type:ticket")
self.print_result(results)
self.assertEqual(2, results.hits)
self.assertEqual(RETARGET_MILESTONE, results.docs[0]["milestone"])
self.assertEqual(RETARGET_MILESTONE, results.docs[1]["milestone"])
def test_fills_product_field_if_product_is_set(self):
with self.product('p'):
self.insert_milestone("T1")
results = self.search_api.query("*")
self.assertEqual(results.docs[0]["product"], 'p')
def test_can_work_if_env_does_not_have_product(self):
if 'product' in self.env:
del self.env["product"]
self.insert_milestone("T1")
results = self.search_api.query("*")
self.assertEqual(results.hits, 1)
self.assertNotIn("product", results.docs[0])
class MilestoneSearchParticipantTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(MilestoneSearchParticipantTestCase, self).setUp()
self.milestone_search = MilestoneSearchParticipant(self.env)
def test_can_get_default_grid_fields(self):
grid_fields = self.milestone_search.get_default_view_fields("grid")
self.env.log.debug("grid_fields: %s", grid_fields)
self.assertGreater(len(grid_fields), 0)
def test_can_get_default_facets(self):
default_facets = self.milestone_search.get_default_facets()
self.env.log.debug("default_facets: %s", default_facets)
self.assertIsNotNone(default_facets)
def test_can_get_is_grid_view_defaults(self):
default_grid_fields = self.milestone_search.get_default_view_fields(
"grid")
self.env.log.debug("default_grid_fields: %s", default_grid_fields)
self.assertIsNotNone(default_grid_fields)
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(
unittest.makeSuite(MilestoneIndexerEventsTestCase, 'test'))
test_suite.addTest(
unittest.makeSuite(MilestoneSearchParticipantTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/wiki_search.py | bloodhound_search/bhsearch/tests/search_resources/wiki_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import shutil
from trac.wiki import WikiSystem, WikiPage
from bhsearch.api import BloodhoundSearchApi
from bhsearch.query_parser import DefaultQueryParser
from bhsearch.search_resources.wiki_search import (
WikiIndexer, WikiSearchParticipant)
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
class WikiIndexerSilenceOnExceptionTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(WikiIndexerSilenceOnExceptionTestCase, self).setUp()
self.env.config.set('bhsearch', 'silence_on_error', "True")
self.wiki_indexer = WikiIndexer(self.env)
def tearDown(self):
pass
def test_does_not_raise_exception_on_add(self):
self.wiki_indexer.wiki_page_added(None)
def test_raise_exception_if_configured(self):
self.env.config.set('bhsearch', 'silence_on_error', "False")
self.assertRaises(
Exception,
self.wiki_indexer.wiki_page_added,
None)
class WikiIndexerEventsTestCase(BaseBloodhoundSearchTest):
DUMMY_PAGE_NAME = "dummyName"
def setUp(self):
super(WikiIndexerEventsTestCase, self).setUp()
self.wiki_system = WikiSystem(self.env)
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
self.wiki_participant = WikiSearchParticipant(self.env)
self.query_parser = DefaultQueryParser(self.env)
def tearDown(self):
shutil.rmtree(self.env.path)
self.env.reset_db()
def test_can_add_new_wiki_page_to_index(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME, "dummy text")
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual(self.DUMMY_PAGE_NAME, doc["id"])
self.assertEqual("dummy text", doc["content"])
self.assertEqual("wiki", doc["type"])
def test_can_delete_wiki_page_from_index(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME)
WikiPage(self.env, self.DUMMY_PAGE_NAME).delete()
#act
results = self.search_api.query("*.*")
#assert
self.print_result(results)
self.assertEqual(0, results.hits)
def test_can_index_changed_event(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME, "Text to be changed")
page = WikiPage(self.env, self.DUMMY_PAGE_NAME)
page.text = "changed text with keyword"
page.save("anAuthor", "some comment", "::1")
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual("changed text with keyword", doc["content"])
def test_can_index_renamed_event(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME)
page = WikiPage(self.env, self.DUMMY_PAGE_NAME)
page.rename("NewPageName")
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
self.assertEqual("NewPageName", results.docs[0]["id"])
def test_can_index_version_deleted_event(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME, "version1")
page = WikiPage(self.env, self.DUMMY_PAGE_NAME)
page.text = "version 2"
page.save("anAuthor", "some comment", "::1")
page.delete(version=2)
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
self.assertEqual("version1", results.docs[0]["content"])
def test_can_strip_wiki_formatting(self):
#arrange
self.insert_wiki(self.DUMMY_PAGE_NAME, " = Header")
#act
results = self.search_api.query("*:*")
#assert
self.print_result(results)
self.assertEqual(1, results.hits)
self.assertEqual("Header", results.docs[0]["content"])
def test_fills_product_field_if_product_is_set(self):
with self.product('p'):
self.insert_wiki(self.DUMMY_PAGE_NAME, "content")
results = self.search_api.query("*")
self.assertEqual(results.docs[0]["product"], 'p')
def test_can_work_if_env_does_not_have_product(self):
if 'product' in self.env:
del self.env["product"]
self.insert_wiki(self.DUMMY_PAGE_NAME, "content")
results = self.search_api.query("*")
self.assertEqual(results.hits, 1)
self.assertNotIn("product", results.docs[0])
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(
WikiIndexerSilenceOnExceptionTestCase, 'test'))
test_suite.addTest(unittest.makeSuite(WikiIndexerEventsTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/changeset_search.py | bloodhound_search/bhsearch/tests/search_resources/changeset_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.core import Component, implements
from trac.versioncontrol import Changeset
from trac.versioncontrol.api import (
IRepositoryConnector, Repository, RepositoryManager)
from bhsearch.api import BloodhoundSearchApi
from bhsearch.search_resources.changeset_search import (
ChangesetSearchParticipant)
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
from bhsearch.whoosh_backend import WhooshBackend
class ChangesetIndexerEventsTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(ChangesetIndexerEventsTestCase, self).setUp()
self.whoosh_backend = WhooshBackend(self.env)
self.whoosh_backend.recreate_index()
self.search_api = BloodhoundSearchApi(self.env)
self.repository_manager = RepositoryManager(self.env)
self.inject_dummy_repository()
def test_can_index_added_changeset(self):
rev = self.insert_changeset("Changed document 1.")
results = self.search_api.query("*:*")
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual('%s/dummy' % rev, doc["id"])
self.assertEqual('dummy', doc["repository"])
self.assertEqual('1', doc["revision"])
self.assertEqual("Changed document 1.", doc["message"])
def test_can_index_modified_changeset(self):
rev = self.insert_changeset("Changed document 1.")
self.modify_changeset(rev, "Added document 1.")
results = self.search_api.query("*:*")
self.assertEqual(1, results.hits)
doc = results.docs[0]
self.assertEqual('%s/dummy' % rev, doc["id"])
self.assertEqual('dummy', doc["repository"])
self.assertEqual('1', doc["revision"])
self.assertEqual("Added document 1.", doc["message"])
def insert_changeset(self, message, author=None, date=None, revision=None):
rev = self.repository.add_changeset(revision, message, author, date)
self.repository_manager.notify("changeset_added", 'dummy', [rev])
return rev
def modify_changeset(self, rev, message=None, author=None, date=None):
changeset = self.repository.get_changeset(rev)
if message is not None:
changeset.message = message
if author is not None:
changeset.author = author
if date is not None:
changeset.date = date
self.repository_manager.notify("changeset_modified", "dummy", [rev])
def inject_dummy_repository(self):
# pylint: disable=protected-access,attribute-defined-outside-init
self.repository = DummyRepositry()
self.repository_connector = DummyRepositoryConnector(self.env)
self.repository_connector.repository = self.repository
self.repository_manager._all_repositories = {
'dummy': dict(dir='dirname', type='dummy')}
self.repository_manager._connectors = {
'dummy': (self.repository_connector, 100)}
class ChangesetSearchParticipantTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(ChangesetSearchParticipantTestCase, self).setUp()
self.changeset_search = ChangesetSearchParticipant(self.env)
def test_can_get_default_grid_fields(self):
grid_fields = self.changeset_search.get_default_view_fields("grid")
self.env.log.debug("grid_fields: %s", grid_fields)
self.assertGreater(len(grid_fields), 0)
def test_can_get_default_facets(self):
default_facets = self.changeset_search.get_default_facets()
self.env.log.debug("default_facets: %s", default_facets)
self.assertIsNotNone(default_facets)
def test_can_get_is_grid_view_defaults(self):
default_grid_fields = self.changeset_search.get_default_view_fields(
"grid")
self.env.log.debug("default_grid_fields: %s", default_grid_fields)
self.assertIsNotNone(default_grid_fields)
class DummyRepositoryConnector(Component):
implements(IRepositoryConnector)
repository = None
def get_supported_types(self):
return ('dummy', 100)
def get_repository(self, repos_type, repos_dir, params):
# pylint: disable=unused-argument
return self.repository
class DummyRepositry(Repository):
# pylint: disable=abstract-method
name = "dummy.git"
def __init__(self):
super(DummyRepositry, self).__init__(
"DummyRepo", dict(name='dummy', id='id'), None)
self.changesets = {}
self.revisions = []
self.last_rev = 0
def add_changeset(self, rev, message, author, date, changes=()):
if rev is None:
rev = self.last_rev = self.last_rev + 1
changeset = Changeset(self, str(rev), message, author, date)
changeset.get_changes = lambda: changes
self.changesets[changeset.rev] = changeset
self.revisions.append(changeset.rev)
return str(rev)
def get_changeset(self, rev):
return self.changesets[rev]
def get_changesets(self, start, stop):
for rev in self.revisions:
yield self.changesets[rev]
def normalize_rev(self, rev):
return rev
def get_changes(self, old_path, old_rev, new_path, new_rev,
ignore_ancestry=1):
return ()
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(
unittest.makeSuite(ChangesetIndexerEventsTestCase, 'test'))
test_suite.addTest(
unittest.makeSuite(ChangesetSearchParticipantTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/__init__.py | bloodhound_search/bhsearch/tests/search_resources/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from bhsearch.tests import unittest
from bhsearch.tests.search_resources import base, changeset_search, \
milestone_search, ticket_search, wiki_search
def suite():
suite = unittest.TestSuite()
suite.addTest(base.suite())
suite.addTest(changeset_search.suite())
suite.addTest(milestone_search.suite())
suite.addTest(ticket_search.suite())
suite.addTest(wiki_search.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/tests/search_resources/base.py | bloodhound_search/bhsearch/tests/search_resources/base.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.test import MockPerm
from trac.web import Href
from trac.wiki import format_to_html
from bhsearch.search_resources.base import SimpleSearchWikiSyntaxFormatter
from bhsearch.tests import unittest
from bhsearch.tests.base import BaseBloodhoundSearchTest
class SimpleSearchWikiSyntaxFormatterTestCase(BaseBloodhoundSearchTest):
def setUp(self):
super(SimpleSearchWikiSyntaxFormatterTestCase, self).setUp(
create_req=True,
)
self.text_formatter = SimpleSearchWikiSyntaxFormatter(self.env)
def test_can_format_header(self):
wiki_content = """= Header #overview
some text"""
result = self._call_format(wiki_content)
self.assertEqual("Header overview some text", result)
def test_can_format_code(self):
wiki_content = """{{{
some code
}}}
text"""
result = self._call_format(wiki_content)
self.assertEqual("some code text", result)
def test_can_format_anchor(self):
wiki_content = """sometext1
[#point1]
sometext2
"""
result = self._call_format(wiki_content)
self.assertEqual("sometext1 point1 sometext2", result)
def test_can_format_wiki_link(self):
self.assertEqual(
"wiki:SomePage p1", self._call_format("[wiki:SomePage p1]"))
def test_can_format_sample_wiki_link(self):
self.assertEqual("WikiPage", self._call_format("WikiPage"))
def test_can_format_makro(self):
"""
Makro links must be formatted as text
"""
self.assertEqual(
"TicketQuery(keywords~x, formattable, colid)",
self._call_format(
"[[TicketQuery(keywords=~x, format=table, col=id)]]"))
def test_can_format_stared_font_makers(self):
self.assertEqual(
"bold, italic, WikiCreole style",
self._call_format(
"**bold**, //italic//, **//WikiCreole style//**"))
@unittest.skip("TODO")
def test_can_format_non_wiki_camel_case(self):
self.assertEqual("WikiPage", self._call_format("!WikiPage"))
def _call_format(self, wiki_content):
result = self.text_formatter.format(wiki_content)
self.env.log.debug(
"Input text:\n%s\nFormatted text:\n%s",
wiki_content,
result)
return result
@unittest.skip("Use for debug purposes only")
def test_run_html_formatter(self):
wiki_content = "!WikiSyntax"
page = self.create_wiki("Dummy wiki", wiki_content)
from trac.mimeview.api import RenderingContext
context = RenderingContext(
page.resource,
href=Href('/'),
perm=MockPerm(),
)
context.req = None # 1.0 FIXME .req shouldn't be required by formatter
format_to_html(self.env, context, wiki_content)
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(
unittest.makeSuite(SimpleSearchWikiSyntaxFormatterTestCase, 'test'))
return test_suite
if __name__ == '__main__':
unittest.main()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/ticket_search.py | bloodhound_search/bhsearch/search_resources/ticket_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Ticket specifics for Bloodhound Search plugin."""
from bhsearch import BHSEARCH_CONFIG_SECTION
from bhsearch.api import (ISearchParticipant, BloodhoundSearchApi,
IIndexParticipant, IndexFields)
from bhsearch.search_resources.base import BaseIndexer, BaseSearchParticipant
from bhsearch.utils import get_product
from genshi.builder import tag
from trac.ticket.api import TicketSystem
from trac.ticket import Ticket
from trac.config import ListOption, Option
from trac.core import implements
from trac.resource import IResourceChangeListener
from trac.ticket.model import Component
TICKET_TYPE = u"ticket"
class TicketFields(IndexFields):
SUMMARY = "summary"
MILESTONE = 'milestone'
COMPONENT = 'component'
KEYWORDS = "keywords"
RESOLUTION = "resolution"
CHANGES = 'changes'
OWNER = 'owner'
class TicketIndexer(BaseIndexer):
implements(IResourceChangeListener, IIndexParticipant)
optional_fields = {
'component': TicketFields.COMPONENT,
'description': TicketFields.CONTENT,
'keywords': TicketFields.KEYWORDS,
'milestone': TicketFields.MILESTONE,
'summary': TicketFields.SUMMARY,
'status': TicketFields.STATUS,
'resolution': TicketFields.RESOLUTION,
'reporter': TicketFields.AUTHOR,
'owner': TicketFields.OWNER,
}
def __init__(self):
self.fields = TicketSystem(self.env).get_ticket_fields()
self.text_area_fields = set(
f['name'] for f in self.fields if f['type'] =='textarea')
#IResourceChangeListener methods
def match_resource(self, resource):
if isinstance(resource, (Component, Ticket)):
return True
return False
def resource_created(self, resource, context):
# pylint: disable=unused-argument
if isinstance(resource, Ticket):
self._index_ticket(resource)
def resource_changed(self, resource, old_values, context):
# pylint: disable=unused-argument
if isinstance(resource, Ticket):
self._index_ticket(resource)
elif isinstance(resource, Component):
self._component_changed(resource, old_values)
def resource_deleted(self, resource, context):
# pylint: disable=unused-argument
if isinstance(resource, Ticket):
self._ticket_deleted(resource)
def resource_version_deleted(self, resource, context):
pass
def _component_changed(self, component, old_values):
if "name" in old_values:
old_name = old_values["name"]
try:
search_api = BloodhoundSearchApi(self.env)
with search_api.start_operation() as operation_context:
TicketIndexer(self.env).reindex_tickets(
search_api,
operation_context,
component=component.name)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during renaming Component \
from %s to %s. The error will not be propagated. \
Exception: %s",
old_name, component.name, e)
else:
raise
def _ticket_deleted(self, ticket):
"""Called when a ticket is deleted."""
try:
search_api = BloodhoundSearchApi(self.env)
search_api.delete_doc(ticket.product, TICKET_TYPE, ticket.id)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during deleting ticket. \
The error will not be propagated. Exception: %s", e)
else:
raise
def reindex_tickets(self,
search_api,
operation_context,
**kwargs):
for ticket in self._fetch_tickets(**kwargs):
self._index_ticket(ticket, search_api, operation_context)
def _fetch_tickets(self, **kwargs):
for ticket_id in self._fetch_ids(**kwargs):
yield Ticket(self.env, ticket_id)
def _fetch_ids(self, **kwargs):
sql = "SELECT id FROM ticket"
args = []
conditions = []
for key, value in kwargs.iteritems():
args.append(value)
conditions.append(key + "=%s")
if conditions:
sql = sql + " WHERE " + " AND ".join(conditions)
for row in self.env.db_query(sql, args):
yield int(row[0])
def _index_ticket(self, ticket, search_api=None, operation_context=None):
try:
if not search_api:
search_api = BloodhoundSearchApi(self.env)
doc = self.build_doc(ticket)
search_api.add_doc(doc, operation_context)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during ticket indexing. \
The error will not be propagated. Exception: %s", e)
else:
raise
#IIndexParticipant members
def build_doc(self, trac_doc):
ticket = trac_doc
searchable_name = '#%(ticket.id)s %(ticket.id)s' %\
{'ticket.id': ticket.id}
doc = {
IndexFields.ID: str(ticket.id),
IndexFields.NAME: searchable_name,
'_stored_' + IndexFields.NAME: str(ticket.id),
IndexFields.TYPE: TICKET_TYPE,
IndexFields.TIME: ticket.time_changed,
IndexFields.PRODUCT: get_product(self.env).prefix,
}
# TODO: Add support for moving tickets between products.
for field, index_field in self.optional_fields.iteritems():
if field in ticket.values:
field_content = ticket.values[field]
if field in self.text_area_fields:
field_content = self.wiki_formatter.format(field_content)
doc[index_field] = field_content
doc[TicketFields.CHANGES] = u'\n\n'.join(
[self.wiki_formatter.format(x[4]) for x in ticket.get_changelog()
if x[2] == u'comment'])
return doc
def get_entries_for_index(self):
for ticket in self._fetch_tickets():
yield self.build_doc(ticket)
class TicketSearchParticipant(BaseSearchParticipant):
implements(ISearchParticipant)
participant_type = TICKET_TYPE
required_permission = 'TICKET_VIEW'
default_facets = [
IndexFields.PRODUCT,
TicketFields.STATUS,
TicketFields.MILESTONE,
TicketFields.COMPONENT,
]
default_grid_fields = [
TicketFields.ID,
TicketFields.SUMMARY,
TicketFields.STATUS,
TicketFields.MILESTONE,
TicketFields.COMPONENT,
]
prefix = TICKET_TYPE
default_facets = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_facets',
default=",".join(default_facets),
doc="""Default facets applied to search view of specific resource""",
doc_domain='bhsearch')
default_view = Option(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_view',
doc = """If true, show grid as default view for specific resource in
Bloodhound Search results""", doc_domain='bhsearch')
default_grid_fields = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_grid_fields',
default = ",".join(default_grid_fields),
doc="""Default fields for grid view for specific resource""",
doc_domain='bhsearch')
#ISearchParticipant members
def get_title(self):
return "Ticket"
def format_search_results(self, res):
if not TicketFields.STATUS in res:
stat = 'undefined_status'
css_class = 'undefined_status'
else:
css_class = res[TicketFields.STATUS]
if res[TicketFields.STATUS] == 'closed':
resolution = ""
if 'resolution' in res:
resolution = res['resolution']
stat = '%s: %s' % (res['status'], resolution)
else:
stat = res[TicketFields.STATUS]
id = res['hilited_id'] or res['id']
id = tag.span(u'#', id, class_=css_class)
summary = res['hilited_summary'] or res['summary']
product = res.get('product')
if product:
return tag(u'[', product, u'] ', id, u': ', summary, u' (%s)' % stat)
else:
return tag(id, u': ', summary, u' (%s)' % stat)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/milestone_search.py | bloodhound_search/bhsearch/search_resources/milestone_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Milestone specifics for Bloodhound Search plugin."""
from bhsearch import BHSEARCH_CONFIG_SECTION
from bhsearch.api import (IIndexParticipant, BloodhoundSearchApi, IndexFields,
ISearchParticipant)
from bhsearch.search_resources.base import BaseIndexer, BaseSearchParticipant
from bhsearch.search_resources.ticket_search import TicketIndexer
from bhsearch.utils import get_product
from trac.ticket import Milestone
from trac.config import ListOption, Option
from trac.core import implements
from trac.resource import IResourceChangeListener
from genshi.builder import tag
MILESTONE_TYPE = u"milestone"
class MilestoneFields(IndexFields):
DUE = "due"
COMPLETED = "completed"
class MilestoneIndexer(BaseIndexer):
implements(IResourceChangeListener, IIndexParticipant)
optional_fields = {
'description': MilestoneFields.CONTENT,
'due': MilestoneFields.DUE,
'completed': MilestoneFields.COMPLETED,
}
# IResourceChangeListener methods
def match_resource(self, resource):
if isinstance(resource, Milestone):
return True
return False
def resource_created(self, resource, context):
# pylint: disable=unused-argument
self._index_milestone(resource)
def resource_changed(self, resource, old_values, context):
# pylint: disable=unused-argument
if "name" in old_values:
self._rename_milestone(resource, old_values["name"])
else:
self._index_milestone(resource)
def resource_deleted(self, resource, context):
# pylint: disable=unused-argument
try:
search_api = BloodhoundSearchApi(self.env)
search_api.delete_doc(
get_product(self.env).prefix, MILESTONE_TYPE, resource.name)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during milestone indexing. \
The error will not be propagated. Exception: %s", e)
else:
raise
def _rename_milestone(self, milestone, old_name):
try:
doc = self.build_doc(milestone)
search_api = BloodhoundSearchApi(self.env)
with search_api.start_operation() as operation_context:
search_api.change_doc_id(doc, old_name, operation_context)
TicketIndexer(self.env).reindex_tickets(
search_api, operation_context, milestone=milestone.name)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during renaming milestone from \
%s to %s. The error will not be propagated. Exception: %s",
old_name, milestone.name, e)
else:
raise
def _index_milestone(self, milestone):
try:
doc = self.build_doc(milestone)
search_api = BloodhoundSearchApi(self.env)
search_api.add_doc(doc)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during wiki indexing. \
The error will not be propagated. Exception: %s", e)
else:
raise
#IIndexParticipant members
def build_doc(self, trac_doc):
milestone = trac_doc
#TODO: a lot of improvements must be added here.
if milestone.is_completed:
status = 'completed'
else:
status = 'open'
doc = {
IndexFields.ID: milestone.name,
IndexFields.NAME: milestone.name,
IndexFields.TYPE: MILESTONE_TYPE,
IndexFields.STATUS: status,
IndexFields.PRODUCT: get_product(self.env).prefix,
}
for field, index_field in self.optional_fields.iteritems():
value = getattr(milestone, field, None)
if value is not None:
doc[index_field] = value
return doc
def get_entries_for_index(self):
for milestone in Milestone.select(self.env, include_completed=True):
yield self.build_doc(milestone)
class MilestoneSearchParticipant(BaseSearchParticipant):
implements(ISearchParticipant)
participant_type = MILESTONE_TYPE
required_permission = 'MILESTONE_VIEW'
default_facets = [
IndexFields.PRODUCT,
]
default_grid_fields = [
MilestoneFields.ID, MilestoneFields.DUE, MilestoneFields.COMPLETED]
prefix = MILESTONE_TYPE
default_facets = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_facets',
default=",".join(default_facets),
doc="""Default facets applied to search view of specific resource""",
doc_domain='bhsearch')
default_view = Option(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_view',
doc = """If true, show grid as default view for specific resource in
Bloodhound Search results""", doc_domain='bhsearch')
default_grid_fields = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_grid_fields',
default=",".join(default_grid_fields),
doc="""Default fields for grid view for specific resource""",
doc_domain='bhsearch')
#ISearchParticipant members
def get_title(self):
return "Milestone"
def format_search_results(self, res):
#TODO: add better milestone rendering
name = res['hilited_name'] or res['name']
product = res.get('product')
if product:
return tag(u'[', product, u'] Milestone:', name)
else:
return tag(u'Milestone:', name)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/wiki_search.py | bloodhound_search/bhsearch/search_resources/wiki_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Wiki specifics for Bloodhound Search plugin."""
from bhsearch import BHSEARCH_CONFIG_SECTION
from bhsearch.api import (ISearchParticipant, BloodhoundSearchApi,
IIndexParticipant, IndexFields)
from bhsearch.search_resources.base import BaseIndexer, BaseSearchParticipant
from bhsearch.utils import get_product
from trac.core import implements
from trac.config import ListOption, Option
from trac.wiki import IWikiChangeListener, WikiSystem, WikiPage
from genshi.builder import tag
WIKI_TYPE = u"wiki"
class WikiIndexer(BaseIndexer):
implements(IWikiChangeListener, IIndexParticipant)
#IWikiChangeListener methods
def wiki_page_added(self, page):
"""Index a recently created ticket."""
self._index_wiki(page)
def wiki_page_changed(self, page, version, t, comment, author, ipnr):
"""Reindex a recently modified ticket."""
# pylint: disable=too-many-arguments, unused-argument
self._index_wiki(page)
def wiki_page_deleted(self, page):
"""Called when a ticket is deleted."""
try:
search_api = BloodhoundSearchApi(self.env)
search_api.delete_doc(
get_product(self.env).prefix, WIKI_TYPE, page.name)
except Exception, e:
if self.silence_on_error.lower() == "true":
self.log.error("Error occurs during wiki indexing. \
The error will not be propagated. Exception: %s", e)
else:
raise
def wiki_page_version_deleted(self, page):
"""Called when a version of a page has been deleted."""
self._index_wiki(page)
def wiki_page_renamed(self, page, old_name):
"""Called when a page has been renamed."""
try:
doc = self.build_doc(page)
search_api = BloodhoundSearchApi(self.env)
search_api.change_doc_id(doc, old_name)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during renaming wiki from %s \
to %s. The error will not be propagated. Exception: %s",
old_name, page.name, e)
else:
raise
def _index_wiki(self, page):
try:
doc = self.build_doc(page)
search_api = BloodhoundSearchApi(self.env)
search_api.add_doc(doc)
except Exception, e:
page_name = None
if page is not None:
page_name = page.name
if self.silence_on_error:
self.log.error("Error occurs during wiki indexing: %s. \
The error will not be propagated. Exception: %s",
page_name, e)
else:
raise
#IIndexParticipant members
def build_doc(self, trac_doc):
page = trac_doc
#This is very naive prototype implementation
#TODO: a lot of improvements must be added here!!!
searchable_name = page.name + ' ' + \
WikiSystem(self.env).format_page_name(page.name, split=True)
doc = {
IndexFields.ID: page.name,
IndexFields.NAME: searchable_name,
'_stored_' + IndexFields.NAME: page.name,
IndexFields.TYPE: WIKI_TYPE,
IndexFields.TIME: page.time,
IndexFields.AUTHOR: page.author,
IndexFields.CONTENT: self.wiki_formatter.format(page.text),
IndexFields.PRODUCT: get_product(self.env).prefix,
}
return doc
def get_entries_for_index(self):
page_names = WikiSystem(self.env).get_pages()
for page_name in page_names:
page = WikiPage(self.env, page_name)
yield self.build_doc(page)
class WikiSearchParticipant(BaseSearchParticipant):
implements(ISearchParticipant)
participant_type = WIKI_TYPE
required_permission = 'WIKI_VIEW'
default_facets = [
IndexFields.PRODUCT,
]
default_grid_fields = [
IndexFields.ID,
IndexFields.TIME,
IndexFields.AUTHOR,
IndexFields.CONTENT,
]
prefix = WIKI_TYPE
default_facets = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_facets',
default=",".join(default_facets),
doc="""Default facets applied to search view of specific resource""",
doc_domain='bhsearch')
default_view = Option(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_view',
doc = """If true, show grid as default view for specific resource in
Bloodhound Search results""", doc_domain='bhsearch')
default_grid_fields = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_grid_fields',
default = ",".join(default_grid_fields),
doc="""Default fields for grid view for specific resource""",
doc_domain='bhsearch')
#ISearchParticipant members
def get_title(self):
return "Wiki"
def format_search_results(self, res):
title = res['hilited_name'] or res['name']
product = res.get('product')
if product:
return tag(u'[', product, u'] ', title)
else:
return tag(title)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/changeset_search.py | bloodhound_search/bhsearch/search_resources/changeset_search.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from bhsearch import BHSEARCH_CONFIG_SECTION
from trac.versioncontrol.api import IRepositoryChangeListener
from bhsearch.api import (IIndexParticipant, BloodhoundSearchApi, IndexFields,
ISearchParticipant)
from bhsearch.search_resources.base import BaseIndexer, BaseSearchParticipant
from genshi.builder import tag
from trac.config import ListOption, Option
from trac.core import implements
from trac.versioncontrol.api import RepositoryManager
CHANGESET_TYPE = u"changeset"
class ChangesetFields(IndexFields):
MESSAGE = "message"
REPOSITORY = "repository"
REVISION = "revision"
CHANGES = "changes"
class ChangesetIndexer(BaseIndexer):
implements(IRepositoryChangeListener, IIndexParticipant)
# IRepositoryChangeListener methods
def changeset_added(self, repos, changeset):
# pylint: disable=unused-argument
self._index_changeset(changeset)
def changeset_modified(self, repos, changeset, old_changeset):
# pylint: disable=unused-argument
self._index_changeset(changeset)
def _index_changeset(self, changeset):
try:
doc = self.build_doc(changeset)
search_api = BloodhoundSearchApi(self.env)
search_api.add_doc(doc)
except Exception, e:
if self.silence_on_error:
self.log.error("Error occurs during changeset indexing. \
The error will not be propagated. Exception: %s", e)
else:
raise
#IIndexParticipant members
def build_doc(self, trac_doc):
changeset = trac_doc
doc = {
IndexFields.ID: u'%s/%s' % (changeset.rev,
changeset.repos.reponame),
IndexFields.TYPE: CHANGESET_TYPE,
ChangesetFields.MESSAGE: changeset.message,
IndexFields.AUTHOR: changeset.author,
IndexFields.TIME: changeset.date,
ChangesetFields.REPOSITORY: changeset.repos.reponame,
ChangesetFields.REVISION: changeset.repos.short_rev(changeset.rev)
}
return doc
def get_entries_for_index(self):
repository_manager = RepositoryManager(self.env)
for repository in repository_manager.get_real_repositories():
rev = repository.oldest_rev
stop = repository.youngest_rev
while True:
changeset = repository.get_changeset(rev)
yield self.build_doc(changeset)
if rev == stop:
break
rev = repository.next_rev(rev)
class ChangesetSearchParticipant(BaseSearchParticipant):
implements(ISearchParticipant)
participant_type = CHANGESET_TYPE
required_permission = 'CHANGESET_VIEW'
default_facets = [
IndexFields.PRODUCT,
ChangesetFields.REPOSITORY,
ChangesetFields.AUTHOR,
]
default_grid_fields = [
ChangesetFields.REPOSITORY,
ChangesetFields.REVISION,
ChangesetFields.AUTHOR,
ChangesetFields.MESSAGE
]
prefix = CHANGESET_TYPE
default_facets = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_facets',
default=",".join(default_facets),
doc="""Default facets applied to search view of specific resource""",
doc_domain='bhsearch')
default_view = Option(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_view',
doc = """If true, show grid as default view for specific resource in
Bloodhound Search results""", doc_domain='bhsearch')
default_grid_fields = ListOption(
BHSEARCH_CONFIG_SECTION,
prefix + '_default_grid_fields',
default=",".join(default_grid_fields),
doc="""Default fields for grid view for specific resource""",
doc_domain='bhsearch')
#ISearchParticipant members
def get_title(self):
return "Changeset"
def format_search_results(self, res):
message = res['hilited_message'] or res['message']
return tag(u'Changeset [', res['revision'], u']: ', message)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/__init__.py | bloodhound_search/bhsearch/search_resources/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/search_resources/base.py | bloodhound_search/bhsearch/search_resources/base.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Base classes for Bloodhound Search plugin."""
import re
from bhsearch.api import ISearchWikiSyntaxFormatter
from trac.core import Component, implements
from trac.config import BoolOption, ExtensionOption
class BaseIndexer(Component):
"""
This is base class for Bloodhound Search indexers of specific resource
"""
silence_on_error = BoolOption('bhsearch', 'silence_on_error', "True",
"""If true, do not throw an exception during indexing a resource""",
doc_domain='bhsearch')
wiki_formatter = ExtensionOption('bhsearch', 'wiki_syntax_formatter',
ISearchWikiSyntaxFormatter, 'SimpleSearchWikiSyntaxFormatter',
'Name of the component implementing wiki syntax to text formatter \
interface: ISearchWikiSyntaxFormatter.', doc_domain='bhsearch')
class BaseSearchParticipant(Component):
default_view = None
default_grid_fields = None
default_facets = None
participant_type = None
required_permission = None
def get_default_facets(self):
return self.default_facets
def get_default_view(self):
return self.default_view
def get_default_view_fields(self, view):
if view == "grid":
return self.default_grid_fields
return None
def is_allowed(self, req=None):
return (not req or self.required_permission in req.perm)
def get_participant_type(self):
return self.participant_type
def get_required_permission(self):
return self.required_permission
class SimpleSearchWikiSyntaxFormatter(Component):
"""
This class provide very naive formatting of wiki syntax to text
appropriate for indexing and search result presentation.
A lot of things can be improved here.
"""
implements(ISearchWikiSyntaxFormatter)
STRIP_CHARS = re.compile(r'([=#\'\"\*/])')
REPLACE_CHARS = re.compile(r'([=#\[\]\{\}|])')
WHITE_SPACE_RE = re.compile(r'([\s]+)')
def format(self, wiki_content):
if not wiki_content:
return wiki_content
intermediate = self.STRIP_CHARS.sub("", wiki_content)
intermediate = self.REPLACE_CHARS.sub(" ", intermediate)
result = self.WHITE_SPACE_RE.sub(" ", intermediate)
return result.strip()
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/utils/translation.py | bloodhound_search/bhsearch/utils/translation.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Project dashboard for Apache(TM) Bloodhound
Translation functions and classes.
"""
from trac.util.translation import domain_functions
#------------------------------------------------------
# Internationalization
#------------------------------------------------------
_, ngettext, tag_, tagn_, gettext, N_, add_domain = \
domain_functions('bhsearch', ('_', 'ngettext', 'tag_', 'tagn_',
'gettext', 'N_', 'add_domain'))
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_search/bhsearch/utils/__init__.py | bloodhound_search/bhsearch/utils/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
def using_multiproduct(env):
return hasattr(env, 'parent')
def get_global_env(env):
if not using_multiproduct(env) or env.parent is None:
return env
else:
return env.parent
class GlobalProduct(object):
prefix = ""
name = ""
GlobalProduct = GlobalProduct()
def get_product(env):
if not using_multiproduct(env) or env.parent is None:
return GlobalProduct
else:
return env.product
def instance_for_every_env(env, cls):
if not using_multiproduct(env):
return [cls(env)]
else:
global_env = get_global_env(env)
return [cls(global_env)] + \
[cls(env) for env in global_env.all_product_envs()]
# Compatibility code for `ComponentManager.is_enabled`
# (available since Trac 0.12)
def is_enabled(env, cls):
"""Return whether the given component class is enabled.
For Trac 0.11 the missing algorithm is included as fallback.
"""
try:
return env.is_enabled(cls)
except AttributeError:
if cls not in env.enabled:
env.enabled[cls] = env.is_component_enabled(cls)
return env.enabled[cls]
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/setup.py | bloodhound_theme/setup.py | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
from setuptools import setup
extra = {}
try:
from trac.util.dist import get_l10n_js_cmdclass
cmdclass = get_l10n_js_cmdclass()
if cmdclass:
extra['cmdclass'] = cmdclass
extractors = [
('**.py', 'trac.dist:extract_python', None),
('**/templates/**.html', 'genshi', None),
('**/templates/**.txt', 'genshi', {
'template_class': 'genshi.template:TextTemplate'
}),
]
extra['message_extractors'] = {
'bhtheme': extractors,
}
except ImportError:
pass
setup(
name='BloodhoundTheme',
version='0.9.0',
description="Theme for Apache(TM) Bloodhound.",
author="Apache Bloodhound",
license="Apache License v2",
url="https://bloodhound.apache.org/",
keywords="trac plugin theme bloodhound",
packages=['bhtheme'],
package_data={'bhtheme': ['htdocs/*.*', 'htdocs/img/*.*',
'htdocs/js/*.js', 'htdocs/css/*.css',
'templates/*.*', 'locale/*/LC_MESSAGES/*.mo']},
classifiers=[
'Framework :: Trac',
],
install_requires=['BloodhoundDashboardPlugin', 'TracThemeEngine'],
test_suite='bhtheme.tests.suite',
tests_require=['unittest2'] if sys.version_info < (2, 7) else [],
entry_points={
'trac.plugins': ['bhtheme.theme = bhtheme.theme']
},
**extra
)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/bhtheme/translation.py | bloodhound_theme/bhtheme/translation.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
r"""Project dashboard for Apache(TM) Bloodhound
Translation functions and classes.
"""
from trac.util.translation import domain_functions
#------------------------------------------------------
# Internationalization
#------------------------------------------------------
_, ngettext, tag_, tagn_, gettext, N_, add_domain = \
domain_functions('bhtheme', ('_', 'ngettext', 'tag_', 'tagn_',
'gettext', 'N_', 'add_domain'))
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/bhtheme/theme.py | bloodhound_theme/bhtheme/theme.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
from genshi.builder import tag
from genshi.core import TEXT
from genshi.filters.transform import Transformer
from genshi.output import DocType
from trac.config import ListOption, Option
from trac.core import Component, TracError, implements
from trac.mimeview.api import get_mimetype
from trac.resource import get_resource_url, Neighborhood, Resource
from trac.ticket.api import TicketSystem
from trac.ticket.model import Ticket, Milestone
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket.web_ui import TicketModule
from trac.util.compat import set
from trac.util.presentation import to_json
from trac.versioncontrol.web_ui.browser import BrowserModule
from trac.web.api import IRequestFilter, IRequestHandler, ITemplateStreamFilter
from trac.web.chrome import (add_stylesheet, add_warning, INavigationContributor,
ITemplateProvider, prevnext_nav, Chrome, add_script)
from trac.wiki.admin import WikiAdmin
from trac.wiki.formatter import format_to_html
from themeengine.api import ThemeBase, ThemeEngineSystem
from bhdashboard.util import dummy_request
from bhdashboard.web_ui import DashboardModule
from bhdashboard import wiki
from multiproduct.env import ProductEnvironment
from multiproduct.web_ui import PRODUCT_RE, ProductModule
from bhtheme.translation import _, add_domain
try:
from multiproduct.ticket.web_ui import ProductTicketModule
except ImportError:
ProductTicketModule = None
class BloodhoundTheme(ThemeBase):
"""Look and feel of Bloodhound issue tracker.
"""
template = htdocs = css = screenshot = disable_trac_css = True
disable_all_trac_css = True
BLOODHOUND_KEEP_CSS = set(
(
'diff.css', 'code.css'
)
)
BLOODHOUND_TEMPLATE_MAP = {
# Admin
'admin_accountsconfig.html': ('bh_admin_accountsconfig.html', '_modify_admin_breadcrumb'),
'admin_accountsnotification.html': ('bh_admin_accountsnotification.html', '_modify_admin_breadcrumb'),
'admin_basics.html': ('bh_admin_basics.html', '_modify_admin_breadcrumb'),
'admin_components.html': ('bh_admin_components.html', '_modify_admin_breadcrumb'),
'admin_enums.html': ('bh_admin_enums.html', '_modify_admin_breadcrumb'),
'admin_logging.html': ('bh_admin_logging.html', '_modify_admin_breadcrumb'),
'admin_milestones.html': ('bh_admin_milestones.html', '_modify_admin_breadcrumb'),
'admin_perms.html': ('bh_admin_perms.html', '_modify_admin_breadcrumb'),
'admin_plugins.html': ('bh_admin_plugins.html', '_modify_admin_breadcrumb'),
'admin_products.html': ('bh_admin_products.html', '_modify_admin_breadcrumb'),
'admin_repositories.html': ('bh_admin_repositories.html', '_modify_admin_breadcrumb'),
'admin_users.html': ('bh_admin_users.html', '_modify_admin_breadcrumb'),
'admin_versions.html': ('bh_admin_versions.html', '_modify_admin_breadcrumb'),
# no template substitutions below - use the default template,
# but call the modifier nonetheless
'repository_links.html': ('repository_links.html', '_modify_admin_breadcrumb'),
# Preferences
'prefs.html': ('bh_prefs.html', None),
'prefs_account.html': ('bh_prefs_account.html', None),
'prefs_advanced.html': ('bh_prefs_advanced.html', None),
'prefs_datetime.html': ('bh_prefs_datetime.html', None),
'prefs_general.html': ('bh_prefs_general.html', None),
'prefs_keybindings.html': ('bh_prefs_keybindings.html', None),
'prefs_language.html': ('bh_prefs_language.html', None),
'prefs_pygments.html': ('bh_prefs_pygments.html', None),
'prefs_userinterface.html': ('bh_prefs_userinterface.html', None),
# Search
'search.html': ('bh_search.html', '_modify_search_data'),
# Wiki
'wiki_delete.html': ('bh_wiki_delete.html', None),
'wiki_diff.html': ('bh_wiki_diff.html', None),
'wiki_edit.html': ('bh_wiki_edit.html', None),
'wiki_rename.html': ('bh_wiki_rename.html', None),
'wiki_view.html': ('bh_wiki_view.html', '_modify_wiki_page_path'),
# Ticket
'diff_view.html': ('bh_diff_view.html', None),
'manage.html': ('manage.html', '_modify_resource_breadcrumb'),
'milestone_edit.html': ('bh_milestone_edit.html', '_modify_roadmap_page'),
'milestone_delete.html': ('bh_milestone_delete.html', '_modify_roadmap_page'),
'milestone_view.html': ('bh_milestone_view.html', '_modify_roadmap_page'),
'query.html': ('bh_query.html', '_add_products_general_breadcrumb'),
'report_delete.html': ('bh_report_delete.html', '_add_products_general_breadcrumb'),
'report_edit.html': ('bh_report_edit.html', '_add_products_general_breadcrumb'),
'report_list.html': ('bh_report_list.html', '_add_products_general_breadcrumb'),
'report_view.html': ('bh_report_view.html', '_add_products_general_breadcrumb'),
'roadmap.html': ('bh_roadmap.html', '_modify_roadmap_page'),
'ticket.html': ('bh_ticket.html', '_modify_ticket'),
'ticket_delete.html': ('bh_ticket_delete.html', None),
'ticket_preview.html': ('bh_ticket_preview.html', None),
# Attachment
'attachment.html': ('bh_attachment.html', None),
'preview_file.html': ('bh_preview_file.html', None),
# Version control
'browser.html': ('bh_browser.html', '_modify_browser'),
'changeset.html': ('bh_changeset.html', None),
'diff_form.html': ('bh_diff_form.html', None),
'dir_entries.html': ('bh_dir_entries.html', None),
'revisionlog.html': ('bh_revisionlog.html', '_modify_browser'),
# Multi Product
'product_view.html': ('bh_product_view.html', '_add_products_general_breadcrumb'),
'product_list.html': ('bh_product_list.html', '_modify_product_list'),
'product_edit.html': ('bh_product_edit.html', '_add_products_general_breadcrumb'),
# General purpose
'about.html': ('bh_about.html', None),
'history_view.html': ('bh_history_view.html', None),
'timeline.html': ('bh_timeline.html', None),
# Account manager plugin
'account_details.html': ('bh_account_details.html', None),
'login.html': ('bh_login.html', None),
'register.html': ('bh_register.html', None),
'reset_password.html': ('bh_reset_password.html', None),
'user_table.html': ('bh_user_table.html', None),
'verify_email.html': ('bh_verify_email.html', None),
}
BOOTSTRAP_CSS_DEFAULTS = (
# ('XPath expression', ['default', 'bootstrap', 'css', 'classes'])
("body//table[not(contains(@class, 'table'))]", # TODO: Accurate ?
['table', 'table-condensed']),
)
labels_application_short = Option('labels', 'application_short',
'Bloodhound', """A short version of application name most commonly
displayed in text, titles and labels""", doc_domain='bhtheme')
labels_application_full = Option('labels', 'application_full',
'Apache Bloodhound', """This is full name with trade mark and
everything, it is currently used in footers and about page only""",
doc_domain='bhtheme')
labels_footer_left_prefix = Option('labels', 'footer_left_prefix', '',
"""Text to display before full application name in footers""",
doc_domain='bhtheme')
labels_footer_left_postfix = Option('labels', 'footer_left_postfix', '',
"""Text to display after full application name in footers""",
doc_domain='bhtheme')
labels_footer_right = Option('labels', 'footer_right', '',
"""Text to use as the right aligned footer""", doc_domain='bhtheme')
_wiki_pages = None
Chrome.default_html_doctype = DocType.HTML5
implements(IRequestFilter, INavigationContributor, ITemplateProvider,
ITemplateStreamFilter)
from trac.web import main
main.default_tracker = 'http://issues.apache.org/bloodhound'
def _get_whitelabelling(self):
"""Gets the whitelabelling config values"""
return {
'application_short': self.labels_application_short,
'application_full': self.labels_application_full,
'footer_left_prefix': self.labels_footer_left_prefix,
'footer_left_postfix': self.labels_footer_left_postfix,
'footer_right': self.labels_footer_right,
'application_version': application_version
}
# ITemplateStreamFilter methods
def filter_stream(self, req, method, filename, stream, data):
"""Insert default Bootstrap CSS classes if rendering
legacy templates (i.e. determined by template name prefix)
and renames wiki guide links.
"""
tx = Transformer('body')
def add_classes(classes):
"""Return a function ensuring CSS classes will be there for element.
"""
def attr_modifier(name, event):
attrs = event[1][1]
class_list = attrs.get(name, '').split()
self.log.debug('BH Theme : Element classes ' + str(class_list))
out_classes = ' '.join(set(class_list + classes))
self.log.debug('BH Theme : Inserting class ' + out_classes)
return out_classes
return attr_modifier
# Insert default bootstrap CSS classes if necessary
for xpath, classes in self.BOOTSTRAP_CSS_DEFAULTS:
tx = tx.end().select(xpath) \
.attr('class', add_classes(classes))
# Rename wiki guide links
tx = tx.end() \
.select("body//a[contains(@href,'/wiki/%s')]" % wiki.GUIDE_NAME) \
.map(lambda text: wiki.new_name(text), TEXT)
# Rename trac error
app_short = self.labels_application_short
tx = tx.end() \
.select("body//div[@class='error']/h1") \
.map(lambda text: text.replace("Trac", app_short), TEXT)
return stream | tx
# IRequestFilter methods
def pre_process_request(self, req, handler):
"""Pre process request filter"""
def hwiki(*args, **kw):
def new_name(name):
new_name = wiki.new_name(name)
if new_name != name:
if not self._wiki_pages:
wiki_admin = WikiAdmin(self.env)
self._wiki_pages = wiki_admin.get_wiki_list()
if new_name in self._wiki_pages:
return new_name
return name
a = tuple([new_name(x) for x in args])
return req.href.__call__("wiki", *a, **kw)
req.href.wiki = hwiki
return handler
def post_process_request(self, req, template, data, content_type):
"""Post process request filter.
Removes all trac provided css if required"""
if template is None and data is None and \
sys.exc_info() == (None, None, None):
return template, data, content_type
def is_active_theme():
is_active = False
active_theme = ThemeEngineSystem(self.env).theme
if active_theme is not None:
this_theme_name = self.get_theme_names().next()
is_active = active_theme['name'] == this_theme_name
return is_active
req.chrome['labels'] = self._get_whitelabelling()
if data is not None:
data['product_list'] = \
ProductModule.get_product_list(self.env, req)
links = req.chrome.get('links', {})
# replace favicon if appropriate
if self.env.project_icon == 'common/trac.ico':
bh_icon = 'theme/img/bh.ico'
new_icon = {'href': req.href.chrome(bh_icon),
'type': get_mimetype(bh_icon)}
if links.get('icon'):
links.get('icon')[0].update(new_icon)
if links.get('shortcut icon'):
links.get('shortcut icon')[0].update(new_icon)
is_active_theme = is_active_theme()
if self.disable_all_trac_css and is_active_theme:
# Move 'admin' entry from mainnav to metanav
for i, entry in enumerate(req.chrome['nav'].get('mainnav', [])):
if entry['name'] == 'admin':
req.chrome['nav'].setdefault('metanav', []) \
.append(req.chrome['nav']['mainnav'].pop(i))
if self.disable_all_trac_css:
stylesheets = links.get('stylesheet', [])
if stylesheets:
path = '/chrome/common/css/'
_iter = ([ss, ss.get('href', '')] for ss in stylesheets)
links['stylesheet'] = \
[ss for ss, href in _iter if not path in href or
href.rsplit('/', 1)[-1] in self.BLOODHOUND_KEEP_CSS]
template, modifier = \
self.BLOODHOUND_TEMPLATE_MAP.get(template, (template, None))
if modifier is not None:
modifier = getattr(self, modifier)
modifier(req, template, data, content_type, is_active_theme)
if is_active_theme and data is not None:
data['responsive_layout'] = \
self.env.config.getbool('bloodhound', 'responsive_layout',
'true')
data['bhrelations'] = \
self.env.config.getbool('components', 'bhrelations.*', 'false')
if req.locale is not None:
add_script(req, 'theme/bloodhound/%s.js' % req.locale)
return template, data, content_type
# ITemplateProvider methods
def get_htdocs_dirs(self):
"""Ensure dashboard htdocs will be there even if
`bhdashboard.web_ui.DashboardModule` is disabled.
"""
if not self.env.is_component_enabled(DashboardModule):
return DashboardModule(self.env).get_htdocs_dirs()
def get_templates_dirs(self):
"""Ensure dashboard templates will be there even if
`bhdashboard.web_ui.DashboardModule` is disabled.
"""
if not self.env.is_component_enabled(DashboardModule):
return DashboardModule(self.env).get_templates_dirs()
# Request modifiers
def _modify_search_data(self, req, template, data, content_type, is_active):
"""Insert breadcumbs and context navigation items in search web UI
"""
if is_active:
# Insert query string in search box (see bloodhound_theme.html)
req.search_query = data.get('query')
# Context nav
prevnext_nav(req, _('Previous'), _('Next'))
# Breadcrumbs nav
data['resourcepath_template'] = 'bh_path_search.html'
def _modify_wiki_page_path(self, req, template, data, content_type,
is_active):
"""Override wiki breadcrumbs nav items
"""
if is_active:
data['resourcepath_template'] = 'bh_path_wikipage.html'
def _modify_roadmap_page(self, req, template, data, content_type,
is_active):
"""Insert roadmap.css + products breadcrumb
"""
add_stylesheet(req, 'dashboard/css/roadmap.css')
self._add_products_general_breadcrumb(req, template, data,
content_type, is_active)
data['milestone_list'] = [m.name for m in Milestone.select(self.env)]
req.chrome['ctxtnav'] = []
def _modify_ticket(self, req, template, data, content_type, is_active):
"""Ticket modifications
"""
self._modify_resource_breadcrumb(req, template, data, content_type,
is_active)
#add a creation event to the changelog if the ticket exists
ticket = data['ticket']
if ticket.exists:
data['changes'] = [{'comment': '',
'author': ticket['reporter'],
'fields': {u'reported': {'label': u'Reported'},
},
'permanent': 1,
'cnum': 0,
'date': ticket['time'],
},
] + data['changes']
#and set default order
if not req.session.get('ticket_comments_order'):
req.session['ticket_comments_order'] = 'newest'
def _modify_resource_breadcrumb(self, req, template, data, content_type,
is_active):
"""Provides logic for breadcrumb resource permissions
"""
if data and ('ticket' in data.keys()) and data['ticket'].exists:
data['resourcepath_template'] = 'bh_path_ticket.html'
# determine path permissions
for resname, permname in [('milestone', 'MILESTONE_VIEW'),
('product', 'PRODUCT_VIEW')]:
res = Resource(resname, data['ticket'][resname])
data['path_show_' + resname] = permname in req.perm(res)
# add milestone list + current milestone to the breadcrumb
data['milestone_list'] = [m.name
for m in Milestone.select(self.env)]
mname = data['ticket']['milestone']
if mname:
data['milestone'] = Milestone(self.env, mname)
def _modify_admin_breadcrumb(self, req, template, data, content_type, is_active):
# override 'normal' product list with the admin one
def admin_url(prefix):
env = ProductEnvironment.lookup_env(self.env, prefix)
href = ProductEnvironment.resolve_href(env, self.env)
return href.admin()
global_settings = (None, _('(Global settings)'), admin_url(None))
data['admin_product_list'] = [global_settings] + \
ProductModule.get_product_list(self.env, req, admin_url)
if isinstance(req.perm.env, ProductEnvironment):
product = req.perm.env.product
data['admin_current_product'] = \
(product.prefix, product.name,
req.href.products(product.prefix, 'admin'))
else:
data['admin_current_product'] = global_settings
data['resourcepath_template'] = 'bh_path_general.html'
def _modify_browser(self, req, template, data, content_type, is_active):
"""Locate path to file in breadcrumbs area rather than title.
Add browser-specific CSS.
"""
data.update({
'resourcepath_template': 'bh_path_links.html',
'path_depth_limit': 2
})
add_stylesheet(req, 'theme/css/browser.css')
def _add_products_general_breadcrumb(self, req, template, data,
content_type, is_active):
if isinstance(req.perm.env, ProductEnvironment):
data['resourcepath_template'] = 'bh_path_general.html'
def _modify_product_list(self, req, template, data, content_type,
is_active):
"""Transform products list into media list by adding
configured product icon as well as further navigation items.
"""
products = data.pop('products')
context = data['context']
with self.env.db_query as db:
icons = db.execute("""
SELECT product, value FROM bloodhound_productconfig
WHERE product IN (%s) AND section='project' AND
option='icon'""" % ', '.join(["%s"] * len(products)),
tuple(p.prefix for p in products))
icons = dict(icons)
data['thumbsize'] = 64
# FIXME: Gray icon for missing products
no_thumbnail = req.href('chrome/theme/img/bh.ico')
product_ctx = lambda item: context.child(item.resource)
def product_media_data(icons, product):
return dict(href=product.href(),
thumb=icons.get(product.prefix, no_thumbnail),
title=product.name,
description=format_to_html(self.env,
product_ctx(product),
product.description),
links={'extras': (([{'href': req.href.products(
product.prefix, action='edit'),
'title': _('Edit product %(prefix)s',
prefix=product.prefix),
'icon': tag.i(class_='icon-edit'),
'label': _('Edit')},]
if 'PRODUCT_MODIFY' in req.perm
else []) +
[{'href': product.href(),
'title': _('Home page'),
'icon': tag.i(class_='icon-home'),
'label': _('Home')},
{'href': product.href.dashboard(),
'title': _('Tickets dashboard'),
'icon': tag.i(class_='icon-tasks'),
'label': _('Tickets')},
{'href': product.href.wiki(),
'title': _('Wiki'),
'icon': tag.i(class_='icon-book'),
'label': _('Wiki')}]),
'main': {'href': product.href(),
'title': None,
'icon': tag.i(class_='icon-chevron-right'),
'label': _('Browse')}})
data['products'] = [product_media_data(icons, product)
for product in products]
# INavigationContributor methods
def get_active_navigation_item(self, req):
return
def get_navigation_items(self, req):
if 'BROWSER_VIEW' in req.perm and 'VERSIONCONTROL_ADMIN' in req.perm:
bm = self.env[BrowserModule]
if bm and not list(bm.get_navigation_items(req)):
yield ('mainnav', 'browser',
tag.a(_('Source'),
href=req.href.wiki('TracRepositoryAdmin')))
class QCTSelectFieldUpdate(Component):
implements(IRequestHandler)
def match_request(self, req):
return req.path_info == '/update-menus'
def process_request(self, req):
product = req.args.get('product')
fields_to_update = req.args.get('fields_to_update[]');
env = ProductEnvironment(self.env.parent, req.args.get('product'))
ticket_fields = TicketSystem(env).get_ticket_fields()
data = dict([f['name'], f['options']] for f in ticket_fields
if f['type'] == 'select' and f['name'] in fields_to_update)
req.send(to_json(data), 'application/json')
class QuickCreateTicketDialog(Component):
implements(IRequestFilter, IRequestHandler)
qct_fields = ListOption('ticket', 'quick_create_fields',
'product, version, type',
doc="""Multiple selection fields displayed in create ticket menu""",
doc_domain='bhtheme')
def __init__(self, *args, **kwargs):
import pkg_resources
locale_dir = pkg_resources.resource_filename(__name__, 'locale')
add_domain(self.env.path, locale_dir)
super(QuickCreateTicketDialog, self).__init__(*args, **kwargs)
# IRequestFilter(Interface):
def pre_process_request(self, req, handler):
"""Nothing to do.
"""
return handler
def post_process_request(self, req, template, data, content_type):
"""Append necessary ticket data
"""
try:
tm = self._get_ticket_module()
except TracError:
# no ticket module so no create ticket button
return template, data, content_type
if (template, data, content_type) != (None,) * 3: # TODO: Check !
if data is None:
data = {}
dum_req = dummy_request(self.env)
dum_req.perm = req.perm
ticket = Ticket(self.env)
tm._populate(dum_req, ticket, False)
all_fields = dict([f['name'], f]
for f in tm._prepare_fields(dum_req, ticket)
if f['type'] == 'select')
product_field = all_fields.get('product')
if product_field:
# When at product scope, set the default selection to the
# product at current scope. When at global scope the default
# selection is determined by [ticket] default_product
if self.env.product and \
self.env.product.prefix in product_field['options']:
product_field['value'] = self.env.product.prefix
# Transform the options field to dictionary of product
# attributes and filter out products for which user doesn't
# have TICKET_CREATE permission
product_field['options'] = [
dict(value=p,
new_ticket_url=dum_req.href.products(p, 'newticket'),
description=ProductEnvironment.lookup_env(self.env, p)
.product.name
)
for p in product_field['options']
if req.perm.has_permission('TICKET_CREATE',
Neighborhood('product', p)
.child(None, None))]
else:
msg = _("Missing ticket field '%(field)s'.", field='product')
if ProductTicketModule is not None and \
self.env[ProductTicketModule] is not None:
# Display warning alert to users
add_warning(req, msg)
else:
# Include message in logs since this might be a failure
self.log.warning(msg)
data['qct'] = {
'fields': [all_fields[k] for k in self.qct_fields
if k in all_fields],
'hidden_fields': [all_fields[k] for k in all_fields.keys()
if k not in self.qct_fields] }
return template, data, content_type
# IRequestHandler methods
def match_request(self, req):
"""Handle requests sent to /qct
"""
m = PRODUCT_RE.match(req.path_info)
return req.path_info == '/qct' or \
(m and m.group('pathinfo').strip('/') == 'qct')
def process_request(self, req):
"""Forward new ticket request to `trac.ticket.web_ui.TicketModule`
but return plain text suitable for AJAX requests.
"""
try:
tm = self._get_ticket_module()
req.perm.require('TICKET_CREATE')
summary = req.args.pop('field_summary', '')
desc = ""
attrs = dict([k[6:], v] for k, v in req.args.iteritems()
if k.startswith('field_'))
product, tid = self.create(req, summary, desc, attrs, True)
except Exception, exc:
self.log.exception("BH: Quick create ticket failed %s" % (exc,))
req.send(str(exc), 'plain/text', 500)
else:
tres = Neighborhood('product', product)('ticket', tid)
href = req.href
req.send(to_json({'product': product, 'id': tid,
'url': get_resource_url(self.env, tres, href)}),
'application/json')
def _get_ticket_module(self):
ptm = None
if ProductTicketModule is not None:
ptm = self.env[ProductTicketModule]
tm = self.env[TicketModule]
if not (tm is None) ^ (ptm is None):
raise TracError('Unable to load TicketModule (disabled)?')
if tm is None:
tm = ptm
return tm
# Public API
def create(self, req, summary, description, attributes={}, notify=False):
""" Create a new ticket, returning the ticket ID.
PS: Borrowed from XmlRpcPlugin.
"""
if 'product' in attributes:
env = self.env.parent or self.env
if attributes['product']:
env = ProductEnvironment(env, attributes['product'])
else:
env = self.env
t = Ticket(env)
t['summary'] = summary
t['description'] = description
t['reporter'] = req.authname
for k, v in attributes.iteritems():
t[k] = v
t['status'] = 'new'
t['resolution'] = ''
t.insert()
if notify:
try:
tn = TicketNotifyEmail(env)
tn.notify(t, newticket=True)
except Exception, e:
self.log.exception("Failure sending notification on creation "
"of ticket #%s: %s" % (t.id, e))
return t['product'], t.id
from pkg_resources import get_distribution
application_version = get_distribution('BloodhoundTheme').version
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/bhtheme/__init__.py | bloodhound_theme/bhtheme/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/bhtheme/tests/theme.py | bloodhound_theme/bhtheme/tests/theme.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from trac.test import EnvironmentStub
from trac.web.chrome import Chrome
from bhdashboard.web_ui import DashboardModule
from bhtheme.theme import BloodhoundTheme
from bhtheme.tests import unittest
class ThemeTestCase(unittest.TestCase):
def setUp(self):
self.env = EnvironmentStub(enable=('trac.*', 'bhtheme.*'),
default_data=True)
self.bhtheme = BloodhoundTheme(self.env)
def tearDown(self):
self.env.reset_db()
def test_templates_dirs(self):
chrome = Chrome(self.env)
self.assertFalse(self.env.is_component_enabled(DashboardModule))
for dir in self.bhtheme.get_templates_dirs():
self.assertIn(dir, chrome.get_all_templates_dirs())
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ThemeTestCase))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/bloodhound_theme/bhtheme/tests/__init__.py | bloodhound_theme/bhtheme/tests/__init__.py | # -*- coding: UTF-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest
from bhtheme.tests import theme
def suite():
test_suite = unittest.TestSuite()
test_suite.addTest(theme.suite())
return test_suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/setup.py | trac/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2013 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
import sys
from setuptools import setup, find_packages
min_python = (2, 5)
if sys.version_info < min_python:
print "Trac requires Python %d.%d or later" % min_python
sys.exit(1)
if sys.version_info >= (3,):
print "Trac doesn't support Python 3 (yet)"
sys.exit(1)
extra = {}
try:
import babel
extractors = [
('**.py', 'trac.dist:extract_python', None),
('**/templates/**.html', 'genshi', None),
('**/templates/**.txt', 'genshi',
{'template_class': 'genshi.template:NewTextTemplate'}),
]
extra['message_extractors'] = {
'trac': extractors,
'tracopt': extractors,
}
from trac.dist import get_l10n_trac_cmdclass
extra['cmdclass'] = get_l10n_trac_cmdclass()
except ImportError:
pass
try:
import genshi
except ImportError:
print "Genshi is needed by Trac setup, pre-installing"
# give some context to the warnings we might get when installing Genshi
setup(
name = 'Trac',
version = '1.0.1',
description = 'Integrated SCM, wiki, issue tracker and project environment',
long_description = """
Trac is a minimalistic web-based software project management and bug/issue
tracking system. It provides an interface to the Subversion revision control
systems, an integrated wiki, flexible issue tracking and convenient report
facilities.
""",
author = 'Edgewall Software',
author_email = 'trac-dev@googlegroups.com',
license = 'BSD',
url = 'http://trac.edgewall.org/',
download_url = 'http://trac.edgewall.org/wiki/TracDownload',
classifiers = [
'Environment :: Web Environment',
'Framework :: Trac',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Bug Tracking',
'Topic :: Software Development :: Version Control',
],
packages = find_packages(exclude=['*.tests']),
package_data = {
'': ['templates/*'],
'trac': ['htdocs/*.*', 'htdocs/README', 'htdocs/js/*.*',
'htdocs/js/messages/*.*', 'htdocs/css/*.*',
'htdocs/css/jquery-ui/*.*',
'htdocs/css/jquery-ui/images/*.*',
'htdocs/guide/*', 'locale/*/LC_MESSAGES/messages.mo',
'locale/*/LC_MESSAGES/tracini.mo',
'TRAC_VERSION'],
'trac.wiki': ['default-pages/*'],
'trac.ticket': ['workflows/*.ini'],
},
test_suite = 'trac.test.suite',
zip_safe = True,
setup_requires = [
'Genshi>=0.6',
],
install_requires = [
'setuptools>=0.6b1',
'Genshi>=0.6',
],
extras_require = {
'Babel': ['Babel>=0.9.5'],
'Pygments': ['Pygments>=0.6'],
'reST': ['docutils>=0.3'],
'SilverCity': ['SilverCity>=0.9.4'],
'Textile': ['textile>=2.0'],
},
entry_points = """
[console_scripts]
trac-admin = trac.admin.console:run
tracd = trac.web.standalone:main
[trac.plugins]
trac.about = trac.about
trac.admin.console = trac.admin.console
trac.admin.web_ui = trac.admin.web_ui
trac.attachment = trac.attachment
trac.db.mysql = trac.db.mysql_backend
trac.db.postgres = trac.db.postgres_backend
trac.db.sqlite = trac.db.sqlite_backend
trac.mimeview.patch = trac.mimeview.patch
trac.mimeview.pygments = trac.mimeview.pygments[Pygments]
trac.mimeview.rst = trac.mimeview.rst[reST]
trac.mimeview.txtl = trac.mimeview.txtl[Textile]
trac.prefs = trac.prefs.web_ui
trac.search = trac.search.web_ui
trac.ticket.admin = trac.ticket.admin
trac.ticket.batch = trac.ticket.batch
trac.ticket.query = trac.ticket.query
trac.ticket.report = trac.ticket.report
trac.ticket.roadmap = trac.ticket.roadmap
trac.ticket.web_ui = trac.ticket.web_ui
trac.timeline = trac.timeline.web_ui
trac.versioncontrol.admin = trac.versioncontrol.admin
trac.versioncontrol.svn_authz = trac.versioncontrol.svn_authz
trac.versioncontrol.web_ui = trac.versioncontrol.web_ui
trac.web.auth = trac.web.auth
trac.web.session = trac.web.session
trac.wiki.admin = trac.wiki.admin
trac.wiki.interwiki = trac.wiki.interwiki
trac.wiki.macros = trac.wiki.macros
trac.wiki.web_ui = trac.wiki.web_ui
trac.wiki.web_api = trac.wiki.web_api
tracopt.mimeview.enscript = tracopt.mimeview.enscript
tracopt.mimeview.php = tracopt.mimeview.php
tracopt.mimeview.silvercity = tracopt.mimeview.silvercity[SilverCity]
tracopt.perm.authz_policy = tracopt.perm.authz_policy
tracopt.perm.config_perm_provider = tracopt.perm.config_perm_provider
tracopt.ticket.clone = tracopt.ticket.clone
tracopt.ticket.commit_updater = tracopt.ticket.commit_updater
tracopt.ticket.deleter = tracopt.ticket.deleter
tracopt.versioncontrol.git.git_fs = tracopt.versioncontrol.git.git_fs
tracopt.versioncontrol.svn.svn_fs = tracopt.versioncontrol.svn.svn_fs
tracopt.versioncontrol.svn.svn_prop = tracopt.versioncontrol.svn.svn_prop
""",
**extra
)
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/__init__.py | trac/tracopt/__init__.py | python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false | |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/ticket/deleter.py | trac/tracopt/ticket/deleter.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
from genshi.builder import tag
from genshi.filters import Transformer
from genshi.filters.transform import StreamBuffer
from trac.core import Component, TracError, implements
from trac.ticket.model import Ticket
from trac.ticket.web_ui import TicketModule
from trac.util import get_reporter_id
from trac.util.datefmt import from_utimestamp
from trac.util.presentation import captioned_button
from trac.util.translation import _
from trac.web.api import IRequestFilter, IRequestHandler, ITemplateStreamFilter
from trac.web.chrome import ITemplateProvider, add_notice, add_stylesheet
class TicketDeleter(Component):
"""Ticket and ticket comment deleter.
This component allows deleting ticket comments and complete tickets. For
users having `TICKET_ADMIN` permission, it adds a "Delete" button next to
each "Reply" button on the page. The button in the ticket description
requests deletion of the complete ticket, and the buttons in the change
history request deletion of a single comment.
'''Comment and ticket deletion are irreversible (and therefore
''dangerous'') operations.''' For that reason, a confirmation step is
requested. The confirmation page shows the ticket box (in the case of a
ticket deletion) or the ticket change (in the case of a comment deletion).
"""
implements(ITemplateProvider, ITemplateStreamFilter, IRequestFilter,
IRequestHandler)
# ITemplateProvider methods
def get_htdocs_dirs(self):
return []
def get_templates_dirs(self):
from pkg_resources import resource_filename
return [resource_filename(__name__, 'templates')]
# ITemplateStreamFilter methods
def filter_stream(self, req, method, filename, stream, data):
if filename not in ('ticket.html', 'ticket_preview.html'):
return stream
ticket = data.get('ticket')
if not (ticket and ticket.exists
and 'TICKET_ADMIN' in req.perm(ticket.resource)):
return stream
# Insert "Delete" buttons for ticket description and each comment
def delete_ticket():
return tag.form(
tag.div(
tag.input(type='hidden', name='action', value='delete'),
tag.input(type='submit',
value=captioned_button(req, u'–', # 'EN DASH'
_("Delete")),
title=_('Delete ticket'),
class_="trac-delete"),
class_="inlinebuttons"),
action='#', method='get')
def delete_comment():
for event in buffer:
cnum, cdate = event[1][1].get('id')[12:].split('-', 1)
return tag.form(
tag.div(
tag.input(type='hidden', name='action',
value='delete-comment'),
tag.input(type='hidden', name='cnum', value=cnum),
tag.input(type='hidden', name='cdate', value=cdate),
tag.input(type='submit',
value=captioned_button(req, u'–', # 'EN DASH'
_("Delete")),
title=_('Delete comment %(num)s', num=cnum),
class_="trac-delete"),
class_="inlinebuttons"),
action='#', method='get')
buffer = StreamBuffer()
return stream | Transformer('//div[@class="description"]'
'/h3[@id="comment:description"]') \
.after(delete_ticket).end() \
.select('//div[starts-with(@class, "change")]/@id') \
.copy(buffer).end() \
.select('//div[starts-with(@class, "change") and @id]'
'/div[@class="trac-ticket-buttons"]') \
.prepend(delete_comment)
# IRequestFilter methods
def pre_process_request(self, req, handler):
if handler is not TicketModule(self.env):
return handler
action = req.args.get('action')
if action in ('delete', 'delete-comment'):
return self
else:
return handler
def post_process_request(self, req, template, data, content_type):
return template, data, content_type
# IRequestHandler methods
def match_request(self, req):
return False
def process_request(self, req):
id = int(req.args.get('id'))
req.perm('ticket', id).require('TICKET_ADMIN')
ticket = Ticket(self.env, id)
action = req.args['action']
cnum = req.args.get('cnum')
if req.method == 'POST':
if 'cancel' in req.args:
href = req.href.ticket(id)
if action == 'delete-comment':
href += '#comment:%s' % cnum
req.redirect(href)
if action == 'delete':
ticket.delete()
add_notice(req, _('The ticket #%(id)s has been deleted.',
id=ticket.id))
req.redirect(req.href())
elif action == 'delete-comment':
cdate = from_utimestamp(long(req.args.get('cdate')))
ticket.delete_change(cdate=cdate)
add_notice(req, _('The ticket comment %(num)s on ticket '
'#%(id)s has been deleted.',
num=cnum, id=ticket.id))
req.redirect(req.href.ticket(id))
tm = TicketModule(self.env)
data = tm._prepare_data(req, ticket)
tm._insert_ticket_data(req, ticket, data,
get_reporter_id(req, 'author'), {})
data.update(action=action, cdate=None)
if action == 'delete-comment':
data['cdate'] = req.args.get('cdate')
cdate = from_utimestamp(long(data['cdate']))
for change in data['changes']:
if change.get('date') == cdate:
data['change'] = change
data['cnum'] = change.get('cnum')
break
else:
raise TracError(_('Comment %(num)s not found', num=cnum))
add_stylesheet(req, 'common/css/ticket.css')
return 'ticket_delete.html', data, None
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/ticket/commit_updater.py | trac/tracopt/ticket/commit_updater.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
# This plugin was based on the contrib/trac-post-commit-hook script, which
# had the following copyright notice:
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
from __future__ import with_statement
from datetime import datetime
import re
from genshi.builder import tag
from trac.config import BoolOption, Option
from trac.core import Component, implements
from trac.perm import PermissionCache
from trac.resource import Resource
from trac.ticket import Ticket
from trac.ticket.notification import TicketNotifyEmail
from trac.util.datefmt import utc
from trac.util.text import exception_to_unicode
from trac.util.translation import cleandoc_
from trac.versioncontrol import IRepositoryChangeListener, RepositoryManager
from trac.versioncontrol.web_ui.changeset import ChangesetModule
from trac.wiki.formatter import format_to_html
from trac.wiki.macros import WikiMacroBase
class CommitTicketUpdater(Component):
"""Update tickets based on commit messages.
This component hooks into changeset notifications and searches commit
messages for text in the form of:
{{{
command #1
command #1, #2
command #1 & #2
command #1 and #2
}}}
Instead of the short-hand syntax "#1", "ticket:1" can be used as well,
e.g.:
{{{
command ticket:1
command ticket:1, ticket:2
command ticket:1 & ticket:2
command ticket:1 and ticket:2
}}}
In addition, the ':' character can be omitted and issue or bug can be used
instead of ticket.
You can have more than one command in a message. The following commands
are supported. There is more than one spelling for each command, to make
this as user-friendly as possible.
close, closed, closes, fix, fixed, fixes::
The specified tickets are closed, and the commit message is added to
them as a comment.
references, refs, addresses, re, see::
The specified tickets are left in their current status, and the commit
message is added to them as a comment.
A fairly complicated example of what you can do is with a commit message
of:
Changed blah and foo to do this or that. Fixes #10 and #12,
and refs #12.
This will close #10 and #12, and add a note to #12.
"""
implements(IRepositoryChangeListener)
envelope = Option('ticket', 'commit_ticket_update_envelope', '',
"""Require commands to be enclosed in an envelope.
Must be empty or contain two characters. For example, if set to "[]",
then commands must be in the form of [closes #4].""")
commands_close = Option('ticket', 'commit_ticket_update_commands.close',
'close closed closes fix fixed fixes',
"""Commands that close tickets, as a space-separated list.""")
commands_refs = Option('ticket', 'commit_ticket_update_commands.refs',
'addresses re references refs see',
"""Commands that add a reference, as a space-separated list.
If set to the special value <ALL>, all tickets referenced by the
message will get a reference to the changeset.""")
check_perms = BoolOption('ticket', 'commit_ticket_update_check_perms',
'true',
"""Check that the committer has permission to perform the requested
operations on the referenced tickets.
This requires that the user names be the same for Trac and repository
operations.""")
notify = BoolOption('ticket', 'commit_ticket_update_notify', 'true',
"""Send ticket change notification when updating a ticket.""")
ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
ticket_reference = ticket_prefix + '[0-9]+'
ticket_command = (r'(?P<action>[A-Za-z]*)\s*.?\s*'
r'(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
(ticket_reference, ticket_reference))
@property
def command_re(self):
(begin, end) = (re.escape(self.envelope[0:1]),
re.escape(self.envelope[1:2]))
return re.compile(begin + self.ticket_command + end)
ticket_re = re.compile(ticket_prefix + '([0-9]+)')
_last_cset_id = None
# IRepositoryChangeListener methods
def changeset_added(self, repos, changeset):
if self._is_duplicate(changeset):
return
tickets = self._parse_message(changeset.message)
comment = self.make_ticket_comment(repos, changeset)
self._update_tickets(tickets, changeset, comment,
datetime.now(utc))
def changeset_modified(self, repos, changeset, old_changeset):
if self._is_duplicate(changeset):
return
tickets = self._parse_message(changeset.message)
old_tickets = {}
if old_changeset is not None:
old_tickets = self._parse_message(old_changeset.message)
tickets = dict(each for each in tickets.iteritems()
if each[0] not in old_tickets)
comment = self.make_ticket_comment(repos, changeset)
self._update_tickets(tickets, changeset, comment,
datetime.now(utc))
def _is_duplicate(self, changeset):
# Avoid duplicate changes with multiple scoped repositories
cset_id = (changeset.rev, changeset.message, changeset.author,
changeset.date)
if cset_id != self._last_cset_id:
self._last_cset_id = cset_id
return False
return True
def _parse_message(self, message):
"""Parse the commit message and return the ticket references."""
cmd_groups = self.command_re.findall(message)
functions = self._get_functions()
tickets = {}
for cmd, tkts in cmd_groups:
func = functions.get(cmd.lower())
if not func and self.commands_refs.strip() == '<ALL>':
func = self.cmd_refs
if func:
for tkt_id in self.ticket_re.findall(tkts):
tickets.setdefault(int(tkt_id), []).append(func)
return tickets
def make_ticket_comment(self, repos, changeset):
"""Create the ticket comment from the changeset data."""
revstring = str(changeset.rev)
if repos.reponame:
revstring += '/' + repos.reponame
return """\
In [changeset:"%s"]:
{{{
#!CommitTicketReference repository="%s" revision="%s"
%s
}}}""" % (revstring, repos.reponame, changeset.rev, changeset.message.strip())
def _update_tickets(self, tickets, changeset, comment, date):
"""Update the tickets with the given comment."""
perm = PermissionCache(self.env, changeset.author)
for tkt_id, cmds in tickets.iteritems():
try:
self.log.debug("Updating ticket #%d", tkt_id)
save = False
with self.env.db_transaction:
ticket = Ticket(self.env, tkt_id)
ticket_perm = perm(ticket.resource)
for cmd in cmds:
if cmd(ticket, changeset, ticket_perm) is not False:
save = True
if save:
ticket.save_changes(changeset.author, comment, date)
if save:
self._notify(ticket, date)
except Exception, e:
self.log.error("Unexpected error while processing ticket "
"#%s: %s", tkt_id, exception_to_unicode(e))
def _notify(self, ticket, date):
"""Send a ticket update notification."""
if not self.notify:
return
try:
tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=False, modtime=date)
except Exception, e:
self.log.error("Failure sending notification on change to "
"ticket #%s: %s", ticket.id,
exception_to_unicode(e))
def _get_functions(self):
"""Create a mapping from commands to command functions."""
functions = {}
for each in dir(self):
if not each.startswith('cmd_'):
continue
func = getattr(self, each)
for cmd in getattr(self, 'commands_' + each[4:], '').split():
functions[cmd] = func
return functions
# Command-specific behavior
# The ticket isn't updated if all extracted commands return False.
def cmd_close(self, ticket, changeset, perm):
if self.check_perms and not 'TICKET_MODIFY' in perm:
self.log.info("%s doesn't have TICKET_MODIFY permission for #%d",
changeset.author, ticket.id)
return False
ticket['status'] = 'closed'
ticket['resolution'] = 'fixed'
if not ticket['owner']:
ticket['owner'] = changeset.author
def cmd_refs(self, ticket, changeset, perm):
if self.check_perms and not 'TICKET_APPEND' in perm:
self.log.info("%s doesn't have TICKET_APPEND permission for #%d",
changeset.author, ticket.id)
return False
class CommitTicketReferenceMacro(WikiMacroBase):
_domain = 'messages'
_description = cleandoc_(
"""Insert a changeset message into the output.
This macro must be called using wiki processor syntax as follows:
{{{
{{{
#!CommitTicketReference repository="reponame" revision="rev"
}}}
}}}
where the arguments are the following:
- `repository`: the repository containing the changeset
- `revision`: the revision of the desired changeset
""")
def expand_macro(self, formatter, name, content, args={}):
reponame = args.get('repository') or ''
rev = args.get('revision')
repos = RepositoryManager(self.env).get_repository(reponame)
try:
changeset = repos.get_changeset(rev)
message = changeset.message
rev = changeset.rev
resource = repos.resource
except Exception:
message = content
resource = Resource('repository', reponame)
if formatter.context.resource.realm == 'ticket':
ticket_re = CommitTicketUpdater.ticket_re
if not any(int(tkt_id) == int(formatter.context.resource.id)
for tkt_id in ticket_re.findall(message)):
return tag.p("(The changeset message doesn't reference this "
"ticket)", class_='hint')
if ChangesetModule(self.env).wiki_format_messages:
return tag.div(format_to_html(self.env,
formatter.context.child('changeset', rev, parent=resource),
message, escape_newlines=True), class_='message')
else:
return tag.pre(message, class_='message')
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/ticket/clone.py | trac/tracopt/ticket/clone.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
from genshi.builder import tag
from genshi.filters import Transformer
from trac.core import Component, implements
from trac.web.api import ITemplateStreamFilter
from trac.util.presentation import captioned_button
from trac.util.translation import _
class TicketCloneButton(Component):
"""Add a 'Clone' button to the ticket box.
This button is located next to the 'Reply' to description button,
and pressing it will send a request for creating a new ticket
which will be based on the cloned one.
"""
implements(ITemplateStreamFilter)
# ITemplateStreamFilter methods
def filter_stream(self, req, method, filename, stream, data):
if filename == 'ticket.html':
ticket = data.get('ticket')
if ticket and ticket.exists and \
'TICKET_ADMIN' in req.perm(ticket.resource):
filter = Transformer('//h3[@id="comment:description"]')
stream |= filter.after(self._clone_form(req, ticket, data))
return stream
def _clone_form(self, req, ticket, data):
fields = {}
for f in data.get('fields', []):
name = f['name']
if name == 'summary':
fields['summary'] = _("%(summary)s (cloned)",
summary=ticket['summary'])
elif name == 'description':
fields['description'] = \
_("Cloned from #%(id)s:\n----\n%(description)s",
id=ticket.id, description=ticket['description'])
else:
fields[name] = ticket[name]
return tag.form(
tag.div(
tag.input(type="submit", name="clone",
value=captioned_button(req, '+#', _("Clone")),
title=_("Create a copy of this ticket")),
[tag.input(type="hidden", name='field_' + n, value=v)
for n, v in fields.iteritems()],
tag.input(type="hidden", name='preview', value=''),
class_="inlinebuttons"),
method="post", action=req.href.newticket())
| python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/ticket/__init__.py | trac/tracopt/ticket/__init__.py | python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false | |
apache/bloodhound | https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/tracopt/versioncontrol/__init__.py | trac/tracopt/versioncontrol/__init__.py | python | Apache-2.0 | c3e31294e68af99d4e040e64fbdf52394344df9e | 2026-01-05T07:12:43.622011Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.